magicclass package¶
Subpackages¶
- magicclass.ext package
- magicclass.stylesheets package
- magicclass.utils package
- magicclass.widgets package
- Subpackages
- Submodules
- magicclass.widgets.color module
- magicclass.widgets.containers module
- magicclass.widgets.logger module
- magicclass.widgets.misc module
- magicclass.widgets.plot module
- magicclass.widgets.separator module
- magicclass.widgets.sequence module
- magicclass.widgets.utils module
- Module contents
Submodules¶
magicclass.core module¶
- class magicclass.core.MagicClassFactory(name: str, layout: str = 'vertical', labels: bool = True, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, widget_type: str | WidgetType = WidgetType.none, icon_path: str = None, attrs: dict[str, Any] | None = None)[source]¶
Bases:
object
Factory class that can make any magic-class.
- magicclass.core.build_help(ui: MagicTemplate, parent=None) HelpWidget [source]¶
Build a widget for user guide. Once it is built, widget will be cached.
- Parameters
ui (MagicTemplate) -- Magic class UI object.
- Returns
Help of the input UI.
- Return type
- magicclass.core.get_function_gui(ui: MagicTemplate, name: str) FunctionGuiPlus [source]¶
Get the FunctionGui object hidden beneath push button or menu.
This function is a helper function for magicclass.
- Parameters
ui (MagicTemplate) -- Any of a magic-class instance.
name (str) -- Name of method (or strictly speaking, the name of PushButton).
- Returns
FunctionGui object.
- Return type
FunctionGuiPlus
- magicclass.core.magicclass(class_: type | None = None, *, layout: str = 'vertical', labels: bool = True, name: str = None, visible: bool | None = None, close_on_run: bool = None, popup_mode: PopUpModeStr | PopUpMode = None, error_mode: ErrorModeStr | ErrorMode = None, widget_type: WidgetTypeStr | WidgetType = WidgetType.none, icon_path: str = None, stylesheet: str | StyleSheet = None)[source]¶
Decorator that can convert a Python class into a widget.
@magicclass class C: ... ui = C() ui.show() # open GUI
- Parameters
class (type, optional) -- Class to be decorated.
layout (str, "vertical" or "horizontal", default is "vertical") -- Layout of the main widget.
labels (bool, default is True) -- If true, magicgui labels are shown.
name (str, optional) -- Name of GUI.
visible (bool, optional) -- Initial visibility of GUI. Useful when magic class is nested.
close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.
popup (bool, default is True) -- Deprecated.
popup_mode (str or PopUpMode, default is PopUpMode.popup) -- Option of how to popup FunctionGui widget when a button is clicked.
error_mode (str or ErrorMode, default is ErrorMode.msgbox) -- Option of how to raise errors during function calls.
widget_type (WidgetType or str, optional) -- Widget type of container.
icon_path (str, optional) -- Path to the icon image.
stylesheet (str or StyleSheet object, optional) -- Set stylesheet to the widget if given.
- Returns
- Return type
Decorated class or decorator.
- magicclass.core.magiccontext(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon_path: str = None)[source]¶
Decorator that can convert a Python class into a context menu.
- Parameters
class (type, optional) -- Class to be decorated.
close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.
popup (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.
- Returns
- Return type
Decorated class or decorator.
Decorator that can convert a Python class into a menu bar.
- Parameters
class (type, optional) -- Class to be decorated.
close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.
popup (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.
- Returns
- Return type
Decorated class or decorator.
- magicclass.core.magictoolbar(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon_path: str = None)[source]¶
Decorator that can convert a Python class into a menu bar.
- magicclass.core.redo(ui: magicclass._gui._base.MagicTemplate, index: int = - 1) None [source]¶
Redo operation on GUI using recorded macro.
- Parameters
ui (MagicTemplate) -- Target magic-class widget.
index (int, default is -1) -- Which execution will be redone. Any object that support list slicing can be used. By default the last operation will be redone.
magicclass.fields module¶
- class magicclass.fields.FieldGroup(layout: str = 'vertical', labels: bool = True, name: str | None = None, **kwargs)[source]¶
Bases:
magicgui.widgets._bases.widget.Widget
,magicgui.widgets._bases.mixins._OrientationMixin
,MutableSequence
[magicgui.widgets._bases.widget.Widget
]- property callbacks: tuple[typing.Callable, ...]¶
Return callbacks in an immutable way.
- class magicclass.fields.HasFields[source]¶
Bases:
object
A trait implemented with widgets and signals.
Subclasses can easily handle widgets and their value-change signals using the same attribute names.
>>> class A(HasFields): >>> a = vfield(int) >>> b = vfield(str) >>> ins = A() >>> ins.a # type: int >>> ins.widgets.a # type: SpinBox >>> ins.signals.a # type: SignalInstance
- property signals: magicclass.fields.SignalView¶
Return a view of signals.
- property widgets: magicclass.fields.WidgetView¶
Return a view of widgets.
- class magicclass.fields.MagicField(value: Any = UNSET, name: str | None = None, label: str | None = None, annotation: Any = None, widget_type: type | str | None = None, options: dict[str, Any] | None = None, record: bool = True, constructor: Callable[..., Widget] | None = None)[source]¶
Bases:
magicclass.fields._FieldObject
,Generic
[magicclass.fields._W
,magicclass.fields._V
]Field class for magicgui construction.
This object is compatible with dataclass. MagicField object is in "ready for widget construction" state.
- as_getter(obj: Any) Callable[[Any], magicclass.fields._V] [source]¶
Make a function that get the value of Widget or Action.
- property callbacks: tuple[typing.Callable, ...]¶
Return callbacks in an immutable way.
- property constructor: Callable[[...], magicgui.widgets._bases.widget.Widget]¶
Get widget constructor.
- default_object = <object object>¶
- disconnect(func: Callable) None [source]¶
Disconnect callback from the field. This method does NOT disconnect callbacks from widgets that are already created.
- property enabled: bool¶
Get interactivity of returned widgets.
- classmethod from_callable(func: Callable[..., _W]) Self[_W, Any] [source]¶
Use a function as the constructor of MagicField.
- get_action(obj: Any) AbstractAction [source]¶
Get an action from
obj
. This function will be called every time MagicField is referred byobj.field
.
- get_widget(obj: Any) magicclass.fields._W [source]¶
Get a widget from
obj
. This function will be called every time MagicField is referred byobj.field
.
- name: str¶
- property record: bool¶
- to_action() Action | WidgetAction[_W] [source]¶
Create a menu action or a menu widget action from the field.
- Returns
Object that can be added to menu.
- Return type
Action or WidgetAction
- Raises
ValueError -- If there is not enough information to build an action.
- to_widget() magicclass.fields._W [source]¶
Create a widget from the field.
- Returns
Widget object that is ready to be inserted into Container.
- Return type
Widget
- Raises
ValueError -- If there is not enough information to build a widget.
- property tooltip: str¶
Get tooltip of returned widgets.
- property visible: bool¶
Get visibility of returned widgets.
- property widget_type: type[magicgui.widgets._bases.widget.Widget]¶
Return type of the resulting widget.
- wraps(method: Callable | None = None, *, template: Callable | None = None, copy: bool = False)[source]¶
Call the
wraps
class method of magic class.This method is needed when a child magic class is defined outside the main magic class, and integrated into the main magic class by
field
function, like below@magicclass class B: def func(self): ... # pre-definition @magicclass class A: b = field(B) @b.wraps def func(self): # do something
- Parameters
method (Callable, optional) -- Method of parent class.
template (Callable, optional) -- Function template for signature.
copy (bool, default is False) -- If true, wrapped method is still enabled.
- Returns
Same method as input, but has updated signature.
- Return type
Callable
- class magicclass.fields.MagicValueField(value: Any = UNSET, name: str | None = None, label: str | None = None, annotation: Any = None, widget_type: type | str | None = None, options: dict[str, Any] | None = None, record: bool = True, constructor: Callable[..., Widget] | None = None)[source]¶
Bases:
magicclass.fields.MagicField
[magicclass.fields._W
,magicclass.fields._V
]Field class for magicgui construction. Unlike MagicField, object of this class always returns value itself.
- name: str¶
- post_get_hook(hook: Callable[[Any, _V], Any] | Callable[[_V], Any])[source]¶
Define a post-get hook for the field.
If a post-get hook is set, value will always be converted before returned. Following example shows how to convert
x
to a float every time it gets accessed.>>> class A: >>> x = vfield(int) >>> @x.post_get_hook >>> def _x_get(self, value): >>> return float(int)
- Parameters
hook (callable) -- Post-get hook function.
- pre_set_hook(hook: Callable[[Any, Any], _V] | Callable[[Any], _V])[source]¶
Define a pre-set hook for the field.
If a pre-set hook is set, value will always be converted before being set to the widget value. Following example shows how to convert
x
to a string before setting the value>>> class A: >>> x = vfield(str) >>> @x.pre_set_hook >>> def _x_set(self, value): >>> return str(value)
- Parameters
hook (callable) -- Pre-set hook function.
- class magicclass.fields.SignalView(obj: magicclass.fields.HasFields)[source]¶
Bases:
magicclass.fields._View
View of signals.
- class magicclass.fields.WidgetView(obj: magicclass.fields.HasFields)[source]¶
Bases:
magicclass.fields._View
View of widgets.
- magicclass.fields.field(obj: magicclass.fields._X, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X] [source]¶
- magicclass.fields.field(widget_type: type[~ _W], *, name: str | None = 'None', label: str | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicclass.fields._W, Any]
- magicclass.fields.field(obj: type[~ _X], *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X]
- magicclass.fields.field(gui_class: type[_M], *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') MagicField[_M, Any]
- magicclass.fields.field(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: type[~ _W] = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicclass.fields._W, Any]
- magicclass.fields.field(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicField[magicgui.widgets._bases.widget.Widget, Any]
Make a MagicField object.
>>> i = field(1) >>> i = field(widget_type="Slider")
- Parameters
obj (Any, default is UNSET) -- Reference to determine what type of widget will be created. If Widget subclass is given, it will be used as is. If other type of class is given, it will used as type annotation. If an object (not type) is given, it will be assumed to be the default value.
name (str, optional) -- Name of the widget.
label (str, optional) -- Label of the widget.
widget_type (str, optional) -- Widget type. This argument will be sent to
create_widget
function.options (WidgetOptions, optional) -- Widget options. This parameter will be passed to the
options
keyword argument ofcreate_widget
.record (bool, default is True) -- A magic-class specific parameter. If true, record value changes as macro.
- Returns
- Return type
- magicclass.fields.vfield(obj: magicclass.fields._X, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X] [source]¶
- magicclass.fields.vfield(widget_type: type[~ _W], *, name: str | None = 'None', label: str | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicclass.fields._W, Any]
- magicclass.fields.vfield(annotation: type[~ _X], *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicgui.widgets._bases.value_widget.ValueWidget, magicclass.fields._X]
- magicclass.fields.vfield(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: type[~ _W] = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicclass.fields._W, Any]
- magicclass.fields.vfield(obj: Any, *, name: str | None = 'None', label: str | None = 'None', widget_type: str | type[WidgetProtocol] | type[Widget] | None = 'None', options: dict[str, typing.Any] = '{}', record: bool = 'True') magicclass.fields.MagicValueField[magicgui.widgets._bases.widget.Widget, Any]
Make a MagicValueField object.
>>> i = vfield(1) >>> i = vfield(widget_type="Slider")
Unlike MagicField, value itself can be accessed.
>>> ui.i # int is returned >>> ui.i = 3 # set value to the widget.
- Parameters
obj (Any, default is UNSET) -- Reference to determine what type of widget will be created. If Widget subclass is given, it will be used as is. If other type of class is given, it will used as type annotation. If an object (not type) is given, it will be assumed to be the default value.
name (str, optional) -- Name of the widget.
label (str, optional) -- Label of the widget.
widget_type (str, optional) -- Widget type. This argument will be sent to
create_widget
function.options (WidgetOptions, optional) -- Widget options. This parameter will be passed to the
options
keyword argument ofcreate_widget
.record (bool, default is True) -- A magic-class specific parameter. If true, record value changes as macro.
- Returns
- Return type
- magicclass.fields.widget_property(func: Callable[[...], magicclass.fields._W]) magicclass.fields.MagicValueField[magicclass.fields._W, Any] [source]¶
Create a widget property from a function.
Generally, this decorator will be used in line with
HasFields
trait. If a widget has to be initialized depending on the state of the instance, you can define a field using a method.>>> class A(HasFields): >>> def __init__(self, max: int = 10): >>> self._max = max >>> @widget_property >>> def param(self): >>> return SpinBox(value=1, max=self._max)
In this example,
param
is a field object similar to those defined usingvfield
but has a variable argumentmax
.>>> a = A(max=20) >>> a.param # Out: 1 >>> a.param = 4 # OK >>> a.widgets.param # SpinBox with value=1 and max=20
- Parameters
func (callable) -- Widget constructor function.
- Returns
A field with given constructor.
- Return type
magicclass.help module¶
magicclass.signature module¶
- class magicclass.signature.AdditionalOptions[source]¶
Bases:
TypedDict
- copyto: str¶
- gui: bool¶
- into: str¶
- keybinding: str¶
- moveto: str¶
- record: bool¶
- class magicclass.signature.MagicMethodSignature(parameters=None, *, return_annotation, gui_options: Optional[dict[str, dict]] = None, caller_options: Optional[dict[str]] = None, additional_options: Optional[dict[str]] = None)[source]¶
Bases:
magicgui.signature.MagicSignature
This class also retains parameter options for PushButton itself, aside from the FunctionGui options that will be needed when the button is pushed.
- classmethod from_signature(sig: inspect.Signature, gui_options=None, caller_options=None, additional_options=None) magicclass.signature.MagicMethodSignature [source]¶
- replace(*, parameters=<class 'magicclass.signature._void'>, return_annotation: Any = <class 'magicclass.signature._void'>) magicclass.signature.MagicMethodSignature [source]¶
Create a customized copy of the Signature.
Pass
parameters
and/orreturn_annotation
arguments to override them in the new copy.
- magicclass.signature.get_additional_option(obj: Any, option: str, default: Optional[Any] = None)[source]¶
Safely get an additional option from any objects.
- magicclass.signature.upgrade_signature(func, gui_options: Optional[dict] = None, caller_options: Optional[magicgui.types.WidgetOptions] = None, additional_options: Optional[magicclass.signature.AdditionalOptions] = None)[source]¶
Upgrade function signature to MagicMethodSignature. The input function may have a inspect.Signature or magicgui.signature.Magicsignature.
- Parameters
func (callable) -- Input function.
gui_options (dict, optional) -- Options of FunctionGui.
caller_options (WidgetOptions, optional) -- Options of PushButton.
additional_options (AdditionalOptions, optional) -- Additional options that will be used in magic class.
- Returns
Same function with upgraded signature
- Return type
callable
magicclass.testing module¶
magicclass.types module¶
- class magicclass.types.Bound(*args)[source]¶
Bases:
object
Make Annotated type from a MagicField or a method, such as:
from magicclass import magicclass, field @magicclass class MyClass: i = field(int) def func(self, v: Bound[i]): ...
Bound[value]
is identical toAnnotated[Any, {"bind": value}]
.
- class magicclass.types.Choices(*args)[source]¶
Bases:
object
Make Annotated type from a method, such as:
from magicclass import magicclass @magicclass class MyClass: def func(self, v: Choices[(1, 2, 3)]): ...
Choices[value]
is identical toAnnotated[Any, {"choices": value}]
.
- class magicclass.types.List(*args, **kwargs)[source]¶
Bases:
object
Make Annotated type similar to
typing.List
.Arguments annotated with
List[...]
will create aListEdit
with a annotated sub types.
- class magicclass.types.Optional(*args, **kwargs)[source]¶
Bases:
object
Make Annotated type similar to
typing.Optional
.Arguments annotated with
Optional[int]
will create aOptionalWidget
with aSpinBox
as an inner widget.Examples
from magicclass import magicclass, set_options from magicclass.types import Optional
@magicclass class A:
@set_options(a={"options": {"min": -1}}) def f(self, a: Optional[int]):
print(a)
ui = A() ui.show()
- class magicclass.types.Tuple(*args, **kwargs)[source]¶
Bases:
object
Make Annotated type similar to
typing.Tuple
.Arguments annotated with
Tuple[...]
will create aTupleEdit
with a annotated sub types.
- class magicclass.types.WidgetType(value)[source]¶
Bases:
enum.Enum
An enumeration.
- button = 'button'¶
- collapsible = 'collapsible'¶
- draggable = 'draggable'¶
- frame = 'frame'¶
- groupbox = 'groupbox'¶
- hcollapsible = 'hcollapsible'¶
- list = 'list'¶
- mainwindow = 'mainwindow'¶
- none = 'none'¶
- scrollable = 'scrollable'¶
- split = 'split'¶
- stacked = 'stacked'¶
- subwindows = 'subwindows'¶
- tabbed = 'tabbed'¶
- toolbox = 'toolbox'¶
- magicclass.types.bound(obj: Callable[[magicclass.types._W], magicclass.types._V]) type[~_V] [source]¶
- magicclass.types.bound(obj: Callable[[Any, magicclass.types._W], magicclass.types._V]) type[~_V]
- magicclass.types.bound(obj: magicclass.fields.MagicField[magicclass.types._W, magicclass.types._V]) type[~_V]
- magicclass.types.bound(obj: type[~ _W]) type
Function version of Bound[...].
magicclass.wrappers module¶
- exception magicclass.wrappers.Canceled[source]¶
Bases:
RuntimeError
Raised when a function is canceled
- magicclass.wrappers.bind_key(*key) Callable[[magicclass.wrappers.F], magicclass.wrappers.F] [source]¶
Define a keybinding to a button or an action. This function accepts several styles of shortcut expression.
>>> @bind_key("Ctrl-A") # napari style >>> @bind_key("Ctrl", "A") # separately >>> @bind_key(Key.Ctrl + Key.A) # use Key class >>> @bind_key(Key.Ctrl, Key.A) # use Key class separately
- magicclass.wrappers.confirm(*, text: str | None, condition: Callable[..., bool] | str | None, callback: Callable[[str, BaseGui], None] | None = 'None') Callable[[magicclass.wrappers.F], magicclass.wrappers.F] [source]¶
- magicclass.wrappers.confirm(f: magicclass.wrappers.F, *, text: str | None, condition: Callable[..., bool] | str | None, callback: Callable[[str, BaseGui], None] | None = 'None') magicclass.wrappers.F
Confirm if it is OK to run function in GUI.
Useful when the function will irreversibly delete or update something in GUI. Confirmation will be executed only when function is called in GUI.
- Parameters
text (str, optional) -- Confirmation message, such as "Are you sure to run this function?". Format string can also be used here, in which case arguments will be passed. For instance, to execute confirmation on function
f(a, b)
, you can use format string"Running with a = {a} and b = {b}"
then confirmation message will be "Running with a = 1, b = 2" iff(1, 2)
is called. By default, message will be "Do you want to run {name}?" where "name" is the function name.condition (callable or str, optional) -- Condition of when confirmation will show up. If callable, it must accept
condition(self)
and return boolean object. If string, it must be evaluable as literal with input arguments as local namespace. For instance, functionf(a, b)
decorated byconfirm(condition="a < b + 1")
will evaluatea < b + 1
to check if confirmation is needed. Always true by default.callback (callable, optional) -- Callback function when confirmation is needed. Must take a
str
and aBaseGui
object as inputs. By default, message box will be shown. Useful for testing.
- magicclass.wrappers.do_not_record(method: magicclass.wrappers.F) magicclass.wrappers.F [source]¶
Wrapped method will not be recorded in macro.
- magicclass.wrappers.mark_preview(function: Callable, text: str = 'Preview') Callable[[magicclass.wrappers.F], magicclass.wrappers.F] [source]¶
Define a preview of a function.
This decorator is useful for advanced magicgui creation. A "Preview" button appears in the bottom of the widget built from the input function and the decorated function will be called with the same arguments. Following example shows how to define a previewer that prints the content of the selected file.
def func(self, path: Path): ... @mark_preview(func) def _func_prev(self, path: Path): with open(path, mode="r") as f: print(f.read())
- Parameters
function (callable) -- To which function previewer will be defined.
text (str, optional) -- Text of preview button.
- magicclass.wrappers.nogui(method: magicclass.wrappers.F) magicclass.wrappers.F [source]¶
Wrapped method will not be converted into a widget.
- magicclass.wrappers.set_design(width: Optional[int] = None, height: Optional[int] = None, min_width: Optional[int] = None, min_height: Optional[int] = None, max_width: Optional[int] = None, max_height: Optional[int] = None, text: Optional[str] = None, icon_path: Optional[str] = None, font_size: Optional[int] = None, font_family: Optional[int] = None, font_color: Optional[Union[Iterable[float], str]] = None, background_color: Optional[Union[Iterable[float], str]] = None, visible: Optional[bool] = None)[source]¶
Change button/action design by calling setter when the widget is created.
- Parameters
width (int, optional) -- Button width. Call
button.width = width
.height (int, optional) -- Button height. Call
button.height = height
.min_width (int, optional) -- Button minimum width. Call
button.min_width = min_width
.min_height (int, optional) -- Button minimum height. Call
button.min_height = min_height
.max_width (int, optional) -- Button maximum width. Call
button.max_width = max_width
.max_height (int, optional) -- Button maximum height. Call
button.max_height = max_height
.text (str, optional) -- Button text. Call
button.text = text
.icon_path (str, optional) -- Path to icon file.
min_width
andmin_height
will be automatically set to the icon size if not given.font_size (int, optional) -- Font size of the text.
visible (bool default is True) -- Button visibility.
- magicclass.wrappers.set_options(layout: str = 'vertical', labels: bool = True, call_button: bool | str | None = None, auto_call: bool = False, **options) Callable[[F], F] [source]¶
Set MagicSignature to functions.
By decorating a method with this function,
magicgui
will create a widget with these options. These codes are similar in appearance.# A magicgui way @magicgui(a={...}) def func(a): ... # A magicclass way @magicclass class A: @set_options(a={...}) def func(self, a): ...
- Parameters
layout (str, default is "vertical") -- The type of layout to use in FunctionGui. Must be one of {'horizontal', 'vertical'}.
labels (bool, default is True) -- Whether labels are shown in the FunctionGui.
call_button (bool or str, optional) -- If
True
, create an additional button that calls the original function when clicked. If astr
, set the button text. If None (the default), it defaults to True whenauto_call
is False, and False otherwise.auto_call (bool, optional) -- If
True
, changing any parameter in either the GUI or the widget attributes will call the original function with the current settings. by default Falseoptions (dict) -- Parameter options.
Module contents¶
- class magicclass.FieldGroup(layout: str = 'vertical', labels: bool = True, name: str | None = None, **kwargs)[source]¶
Bases:
magicgui.widgets._bases.widget.Widget
,magicgui.widgets._bases.mixins._OrientationMixin
,MutableSequence
[magicgui.widgets._bases.widget.Widget
]- property callbacks: tuple[typing.Callable, ...]¶
Return callbacks in an immutable way.
- class magicclass.HasFields[source]¶
Bases:
object
A trait implemented with widgets and signals.
Subclasses can easily handle widgets and their value-change signals using the same attribute names.
>>> class A(HasFields): >>> a = vfield(int) >>> b = vfield(str) >>> ins = A() >>> ins.a # type: int >>> ins.widgets.a # type: SpinBox >>> ins.signals.a # type: SignalInstance
- property signals: magicclass.fields.SignalView¶
Return a view of signals.
- property widgets: magicclass.fields.WidgetView¶
Return a view of widgets.
- class magicclass.Key(value)[source]¶
Bases:
enum.Enum
An enumeration.
- A = 'a'¶
- Alt = 'alt'¶
- Ampersand = '&'¶
- Apostrophe = "'"¶
- Asterisk = '*'¶
- At = '@'¶
- B = 'b'¶
- Backspace = 'backspace'¶
- C = 'c'¶
- Colon = ':'¶
- Comma = ','¶
- Ctrl = 'ctrl'¶
- D = 'd'¶
- Delete = 'delete'¶
- Dollar = '$'¶
- Down = 'down'¶
- E = 'e'¶
- Equal = '='¶
- Exclam = '!'¶
- F = 'f'¶
- F1 = 'f1'¶
- F10 = 'f10'¶
- F11 = 'f11'¶
- F12 = 'f12'¶
- F2 = 'f2'¶
- F3 = 'f3'¶
- F4 = 'f4'¶
- F5 = 'f5'¶
- F6 = 'f6'¶
- F7 = 'f7'¶
- F8 = 'f8'¶
- F9 = 'f9'¶
- G = 'g'¶
- Greater = '>'¶
- H = 'h'¶
- I = 'i'¶
- J = 'j'¶
- K = 'k'¶
- L = 'l'¶
- Left = 'left'¶
- Less = '<'¶
- M = 'm'¶
- Meta = 'meta'¶
- Minus = '-'¶
- N = 'n'¶
- O = 'o'¶
- P = 'p'¶
- PageDown = 'pagedown'¶
- PageUp = 'pageup'¶
- ParenLeft = '('¶
- ParenRight = ')'¶
- Percent = '%'¶
- Period = '.'¶
- Plus = '+'¶
- Q = 'q'¶
- Question = '?'¶
- R = 'r'¶
- Right = 'right'¶
- S = 's'¶
- Semicolon = ';'¶
- Shift = 'shift'¶
- Slash = '/'¶
- T = 't'¶
- Tab = 'tab'¶
- U = 'u'¶
- Up = 'up'¶
- V = 'v'¶
- W = 'w'¶
- X = 'x'¶
- Y = 'y'¶
- Z = 'z'¶
- class magicclass.MagicTemplate[source]¶
Bases:
object
- annotation: Any¶
- changed: Signal¶
- enabled: bool¶
- find_ancestor(ancestor: type[~ _T]) magicclass._gui._base._T [source]¶
Find magic class ancestor whose type matches the input. This method is useful when a child widget class is defined outside a magic class while it needs access to its parent.
- Parameters
ancestor (type of MagicTemplate) -- Type of ancestor to search for.
- Returns
Magic class object if found.
- Return type
- gui_only: bool¶
- height: int¶
- icon_path: str¶
- label: str¶
- label_changed: Signal¶
- labels: bool¶
- layout: str¶
- property macro: magicclass._gui._macro.GuiMacro¶
The macro object bound to the ancestor widget.
- margins: tuple[int, int, int, int]¶
- max_height: int¶
- max_width: int¶
- min_height: int¶
- min_width: int¶
- name: str¶
- native: QWidget¶
- objectName() str [source]¶
Return object name of the QWidget.
This function makes the object name discoverable by napari's viewer.window.add_dock_widget function. At the same time, since this function will always be called when the widget is added as a dock widget of napari, we can import macro recorders for napari types in the appropriate timing.
- options: dict¶
- param_kind: inspect._ParameterKind¶
- parent: Widget¶
- parent_changed: Signal¶
- property parent_dock_widget: QDockWidget | None¶
Return dock widget object if magic class is a dock widget of a main window widget, such as a napari Viewer.
- property parent_viewer: napari.Viewer | None¶
Return napari.Viewer if magic class is a dock widget of a viewer.
- tooltip: str¶
- visible: bool¶
- widget_type: str¶
- width: int¶
- classmethod wraps(method: _F | None = None, *, template: Callable | None = None, copy: bool = False) _F [source]¶
Wrap a parent method in a child magic-class.
Wrapped method will appear in the child widget but behaves as if it is in the parent widget. Basically, this function is used as a wrapper like below.
@magicclass class C: @magicclass class D: def func(self, ...): ... # pre-definition @D.wraps def func(self, ...): ...
- Parameters
method (Callable, optional) -- Method of parent class.
template (Callable, optional) -- Function template for signature.
copy (bool, default is False) -- If true, wrapped method is still enabled.
- Returns
Same method as input, but has updated signature.
- Return type
Callable
- class magicclass.PopUpMode(value)[source]¶
Bases:
enum.Enum
Define how to popup FunctionGui.
- above = 'above'¶
- below = 'below'¶
- dialog = 'dialog'¶
- dock = 'dock'¶
- first = 'first'¶
- last = 'last'¶
- parentlast = 'parentlast'¶
- popup = 'popup'¶
- magicclass.bind_key(*key) Callable[[magicclass.wrappers.F], magicclass.wrappers.F] [source]¶
Define a keybinding to a button or an action. This function accepts several styles of shortcut expression.
>>> @bind_key("Ctrl-A") # napari style >>> @bind_key("Ctrl", "A") # separately >>> @bind_key(Key.Ctrl + Key.A) # use Key class >>> @bind_key(Key.Ctrl, Key.A) # use Key class separately
- magicclass.build_help(ui: MagicTemplate, parent=None) HelpWidget [source]¶
Build a widget for user guide. Once it is built, widget will be cached.
- Parameters
ui (MagicTemplate) -- Magic class UI object.
- Returns
Help of the input UI.
- Return type
- magicclass.confirm(f: F | None = None, *, text: str | None = None, condition: Callable[[BaseGui], bool] | str = None, callback: Callable[[str, BaseGui], None] | None = None)[source]¶
Confirm if it is OK to run function in GUI.
Useful when the function will irreversibly delete or update something in GUI. Confirmation will be executed only when function is called in GUI.
- Parameters
text (str, optional) -- Confirmation message, such as "Are you sure to run this function?". Format string can also be used here, in which case arguments will be passed. For instance, to execute confirmation on function
f(a, b)
, you can use format string"Running with a = {a} and b = {b}"
then confirmation message will be "Running with a = 1, b = 2" iff(1, 2)
is called. By default, message will be "Do you want to run {name}?" where "name" is the function name.condition (callable or str, optional) -- Condition of when confirmation will show up. If callable, it must accept
condition(self)
and return boolean object. If string, it must be evaluable as literal with input arguments as local namespace. For instance, functionf(a, b)
decorated byconfirm(condition="a < b + 1")
will evaluatea < b + 1
to check if confirmation is needed. Always true by default.callback (callable, optional) -- Callback function when confirmation is needed. Must take a
str
and aBaseGui
object as inputs. By default, message box will be shown. Useful for testing.
- magicclass.do_not_record(method: magicclass.wrappers.F) magicclass.wrappers.F [source]¶
Wrapped method will not be recorded in macro.
- magicclass.field(obj: Any = UNSET, *, name: str | None = None, label: str | None = None, widget_type: str | type[WidgetProtocol] | None = None, options: dict[str, Any] = {}, record: bool = True) MagicField[Widget, Any] [source]¶
Make a MagicField object.
>>> i = field(1) >>> i = field(widget_type="Slider")
- Parameters
obj (Any, default is UNSET) -- Reference to determine what type of widget will be created. If Widget subclass is given, it will be used as is. If other type of class is given, it will used as type annotation. If an object (not type) is given, it will be assumed to be the default value.
name (str, optional) -- Name of the widget.
label (str, optional) -- Label of the widget.
widget_type (str, optional) -- Widget type. This argument will be sent to
create_widget
function.options (WidgetOptions, optional) -- Widget options. This parameter will be passed to the
options
keyword argument ofcreate_widget
.record (bool, default is True) -- A magic-class specific parameter. If true, record value changes as macro.
- Returns
- Return type
- magicclass.get_function_gui(ui: MagicTemplate, name: str) FunctionGuiPlus [source]¶
Get the FunctionGui object hidden beneath push button or menu.
This function is a helper function for magicclass.
- Parameters
ui (MagicTemplate) -- Any of a magic-class instance.
name (str) -- Name of method (or strictly speaking, the name of PushButton).
- Returns
FunctionGui object.
- Return type
FunctionGuiPlus
- magicclass.magicclass(class_: type | None = None, *, layout: str = 'vertical', labels: bool = True, name: str = None, visible: bool | None = None, close_on_run: bool = None, popup_mode: PopUpModeStr | PopUpMode = None, error_mode: ErrorModeStr | ErrorMode = None, widget_type: WidgetTypeStr | WidgetType = WidgetType.none, icon_path: str = None, stylesheet: str | StyleSheet = None)[source]¶
Decorator that can convert a Python class into a widget.
@magicclass class C: ... ui = C() ui.show() # open GUI
- Parameters
class (type, optional) -- Class to be decorated.
layout (str, "vertical" or "horizontal", default is "vertical") -- Layout of the main widget.
labels (bool, default is True) -- If true, magicgui labels are shown.
name (str, optional) -- Name of GUI.
visible (bool, optional) -- Initial visibility of GUI. Useful when magic class is nested.
close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.
popup (bool, default is True) -- Deprecated.
popup_mode (str or PopUpMode, default is PopUpMode.popup) -- Option of how to popup FunctionGui widget when a button is clicked.
error_mode (str or ErrorMode, default is ErrorMode.msgbox) -- Option of how to raise errors during function calls.
widget_type (WidgetType or str, optional) -- Widget type of container.
icon_path (str, optional) -- Path to the icon image.
stylesheet (str or StyleSheet object, optional) -- Set stylesheet to the widget if given.
- Returns
- Return type
Decorated class or decorator.
- magicclass.magiccontext(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon_path: str = None)[source]¶
Decorator that can convert a Python class into a context menu.
- Parameters
class (type, optional) -- Class to be decorated.
close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.
popup (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.
- Returns
- Return type
Decorated class or decorator.
Decorator that can convert a Python class into a menu bar.
- Parameters
class (type, optional) -- Class to be decorated.
close_on_run (bool, default is True) -- If True, magicgui created by every method will be deleted after the method is completed without exceptions, i.e. magicgui is more like a dialog.
popup (bool, default is True) -- If True, magicgui created by every method will be poped up, else they will be appended as a part of the main widget.
- Returns
- Return type
Decorated class or decorator.
- magicclass.magictoolbar(class_: type = None, *, close_on_run: bool = None, popup_mode: str | PopUpMode = None, error_mode: str | ErrorMode = None, labels: bool = True, name: str | None = None, icon_path: str = None)[source]¶
Decorator that can convert a Python class into a menu bar.
- magicclass.mark_preview(function: Callable, text: str = 'Preview') Callable[[magicclass.wrappers.F], magicclass.wrappers.F] [source]¶
Define a preview of a function.
This decorator is useful for advanced magicgui creation. A "Preview" button appears in the bottom of the widget built from the input function and the decorated function will be called with the same arguments. Following example shows how to define a previewer that prints the content of the selected file.
def func(self, path: Path): ... @mark_preview(func) def _func_prev(self, path: Path): with open(path, mode="r") as f: print(f.read())
- Parameters
function (callable) -- To which function previewer will be defined.
text (str, optional) -- Text of preview button.
- magicclass.nogui(method: magicclass.wrappers.F) magicclass.wrappers.F [source]¶
Wrapped method will not be converted into a widget.
- magicclass.redo(ui: magicclass._gui._base.MagicTemplate, index: int = - 1) None [source]¶
Redo operation on GUI using recorded macro.
- Parameters
ui (MagicTemplate) -- Target magic-class widget.
index (int, default is -1) -- Which execution will be redone. Any object that support list slicing can be used. By default the last operation will be redone.
- magicclass.set_design(width: Optional[int] = None, height: Optional[int] = None, min_width: Optional[int] = None, min_height: Optional[int] = None, max_width: Optional[int] = None, max_height: Optional[int] = None, text: Optional[str] = None, icon_path: Optional[str] = None, font_size: Optional[int] = None, font_family: Optional[int] = None, font_color: Optional[Union[Iterable[float], str]] = None, background_color: Optional[Union[Iterable[float], str]] = None, visible: Optional[bool] = None)[source]¶
Change button/action design by calling setter when the widget is created.
- Parameters
width (int, optional) -- Button width. Call
button.width = width
.height (int, optional) -- Button height. Call
button.height = height
.min_width (int, optional) -- Button minimum width. Call
button.min_width = min_width
.min_height (int, optional) -- Button minimum height. Call
button.min_height = min_height
.max_width (int, optional) -- Button maximum width. Call
button.max_width = max_width
.max_height (int, optional) -- Button maximum height. Call
button.max_height = max_height
.text (str, optional) -- Button text. Call
button.text = text
.icon_path (str, optional) -- Path to icon file.
min_width
andmin_height
will be automatically set to the icon size if not given.font_size (int, optional) -- Font size of the text.
visible (bool default is True) -- Button visibility.
- magicclass.set_options(layout: str = 'vertical', labels: bool = True, call_button: bool | str | None = None, auto_call: bool = False, **options) Callable[[F], F] [source]¶
Set MagicSignature to functions.
By decorating a method with this function,
magicgui
will create a widget with these options. These codes are similar in appearance.# A magicgui way @magicgui(a={...}) def func(a): ... # A magicclass way @magicclass class A: @set_options(a={...}) def func(self, a): ...
- Parameters
layout (str, default is "vertical") -- The type of layout to use in FunctionGui. Must be one of {'horizontal', 'vertical'}.
labels (bool, default is True) -- Whether labels are shown in the FunctionGui.
call_button (bool or str, optional) -- If
True
, create an additional button that calls the original function when clicked. If astr
, set the button text. If None (the default), it defaults to True whenauto_call
is False, and False otherwise.auto_call (bool, optional) -- If
True
, changing any parameter in either the GUI or the widget attributes will call the original function with the current settings. by default Falseoptions (dict) -- Parameter options.
- magicclass.vfield(obj: Any = UNSET, *, name: str | None = None, label: str | None = None, widget_type: str | type[WidgetProtocol] | None = None, options: dict[str, Any] = {}, record: bool = True) MagicValueField[Widget, Any] [source]¶
Make a MagicValueField object.
>>> i = vfield(1) >>> i = vfield(widget_type="Slider")
Unlike MagicField, value itself can be accessed.
>>> ui.i # int is returned >>> ui.i = 3 # set value to the widget.
- Parameters
obj (Any, default is UNSET) -- Reference to determine what type of widget will be created. If Widget subclass is given, it will be used as is. If other type of class is given, it will used as type annotation. If an object (not type) is given, it will be assumed to be the default value.
name (str, optional) -- Name of the widget.
label (str, optional) -- Label of the widget.
widget_type (str, optional) -- Widget type. This argument will be sent to
create_widget
function.options (WidgetOptions, optional) -- Widget options. This parameter will be passed to the
options
keyword argument ofcreate_widget
.record (bool, default is True) -- A magic-class specific parameter. If true, record value changes as macro.
- Returns
- Return type
- magicclass.widget_property(func: Callable[[...], magicclass.fields._W]) magicclass.fields.MagicValueField[magicclass.fields._W, Any] [source]¶
Create a widget property from a function.
Generally, this decorator will be used in line with
HasFields
trait. If a widget has to be initialized depending on the state of the instance, you can define a field using a method.>>> class A(HasFields): >>> def __init__(self, max: int = 10): >>> self._max = max >>> @widget_property >>> def param(self): >>> return SpinBox(value=1, max=self._max)
In this example,
param
is a field object similar to those defined usingvfield
but has a variable argumentmax
.>>> a = A(max=20) >>> a.param # Out: 1 >>> a.param = 4 # OK >>> a.widgets.param # SpinBox with value=1 and max=20
- Parameters
func (callable) -- Widget constructor function.
- Returns
A field with given constructor.
- Return type
- magicclass.wraps(template: Callable | inspect.Signature) Callable[[_C], _C] [source]¶
Update signature using a template. If class is wrapped, then all the methods except for those start with "__" will be wrapped.
- Parameters
template (Callable or inspect.Signature object) -- Template function or its signature.
- Returns
A wrapper which take a function or class as an input and returns same function or class with updated signature(s).
- Return type
Callable