diff --git a/api/protocols/index.html b/api/protocols/index.html index 996ee0066..81dad32ba 100644 --- a/api/protocols/index.html +++ b/api/protocols/index.html @@ -5256,7 +5256,7 @@

- Bases: ValueWidgetProtocol, SupportsText, Protocol

+ Bases: ValueWidgetProtocol, SupportsText, SupportsIcon, Protocol

The "value" in a ButtonWidget is the current (checked) state.

diff --git a/generated_examples/applications/callable/index.html b/generated_examples/applications/callable/index.html index 0233acfc0..8695d2e24 100644 --- a/generated_examples/applications/callable/index.html +++ b/generated_examples/applications/callable/index.html @@ -2811,7 +2811,7 @@

Callable functions demoexample.func.changed.connect(update) example.show(run=True) -

Total running time of the script: ( 0 minutes 0.196 seconds)

+

Total running time of the script: ( 0 minutes 0.077 seconds)

Download Python source code: callable.py

diff --git a/generated_examples/applications/callable_codeobj.pickle b/generated_examples/applications/callable_codeobj.pickle index ee3b9af20..c30de6589 100644 Binary files a/generated_examples/applications/callable_codeobj.pickle and b/generated_examples/applications/callable_codeobj.pickle differ diff --git a/generated_examples/applications/chaining/index.html b/generated_examples/applications/chaining/index.html index eb6df81b1..8d1c68a78 100644 --- a/generated_examples/applications/chaining/index.html +++ b/generated_examples/applications/chaining/index.html @@ -2835,7 +2835,7 @@

Chaining functions together# notice which functions get called when you change each widget. -

Total running time of the script: ( 0 minutes 0.110 seconds)

+

Total running time of the script: ( 0 minutes 0.111 seconds)

Download Python source code: chaining.py

diff --git a/generated_examples/applications/chaining_codeobj.pickle b/generated_examples/applications/chaining_codeobj.pickle index 0c5eb9764..c1acba4e7 100644 Binary files a/generated_examples/applications/chaining_codeobj.pickle and b/generated_examples/applications/chaining_codeobj.pickle differ diff --git a/generated_examples/applications/hotdog/index.html b/generated_examples/applications/hotdog/index.html index f82ebb310..811100e10 100644 --- a/generated_examples/applications/hotdog/index.html +++ b/generated_examples/applications/hotdog/index.html @@ -2818,7 +2818,7 @@

Hotdog or not appif __name__ == "__main__": is_hotdog.show(run=True) -

Total running time of the script: ( 0 minutes 0.088 seconds)

+

Total running time of the script: ( 0 minutes 0.087 seconds)

Download Python source code: hotdog.py

diff --git a/generated_examples/applications/hotdog_codeobj.pickle b/generated_examples/applications/hotdog_codeobj.pickle index 7a4444c4c..ae1e9334b 100644 Binary files a/generated_examples/applications/hotdog_codeobj.pickle and b/generated_examples/applications/hotdog_codeobj.pickle differ diff --git a/generated_examples/applications/mg_execution_times/index.html b/generated_examples/applications/mg_execution_times/index.html index 7cf71f56f..28af0d9d7 100644 --- a/generated_examples/applications/mg_execution_times/index.html +++ b/generated_examples/applications/mg_execution_times/index.html @@ -2743,17 +2743,17 @@

Computation times#

-

00:02.718 total execution time for generated_examples_applications files:

+

00:02.569 total execution time for generated_examples_applications files:

+-----------------------------------------------------------------------------------+-----------+--------+ -| pint_quantity (docs/examples/applications/pint_quantity.py) | 00:02.223 | 0.0 MB | +| pint_quantity (docs/examples/applications/pint_quantity.py) | 00:02.190 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ -| callable (docs/examples/applications/callable.py) | 00:00.196 | 0.0 MB | +| chaining (docs/examples/applications/chaining.py) | 00:00.111 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ -| chaining (docs/examples/applications/chaining.py) | 00:00.110 | 0.0 MB | +| snells_law (docs/examples/applications/snells_law.py) | 00:00.104 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ -| snells_law (docs/examples/applications/snells_law.py) | 00:00.101 | 0.0 MB | +| hotdog (docs/examples/applications/hotdog.py) | 00:00.087 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ -| hotdog (docs/examples/applications/hotdog.py) | 00:00.088 | 0.0 MB | +| callable (docs/examples/applications/callable.py) | 00:00.077 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | values_dialog (docs/examples/applications/values_dialog.py) | 00:00.000 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+

diff --git a/generated_examples/applications/pint_quantity/index.html b/generated_examples/applications/pint_quantity/index.html index f1e3930f1..71e306a5d 100644 --- a/generated_examples/applications/pint_quantity/index.html +++ b/generated_examples/applications/pint_quantity/index.html @@ -2799,7 +2799,7 @@

Quantities with pintwidget.show(run=True) -

Total running time of the script: ( 0 minutes 2.223 seconds)

+

Total running time of the script: ( 0 minutes 2.190 seconds)

Download Python source code: pint_quantity.py

diff --git a/generated_examples/applications/pint_quantity_codeobj.pickle b/generated_examples/applications/pint_quantity_codeobj.pickle index 457f62ae8..a2681f5aa 100644 Binary files a/generated_examples/applications/pint_quantity_codeobj.pickle and b/generated_examples/applications/pint_quantity_codeobj.pickle differ diff --git a/generated_examples/applications/snells_law/index.html b/generated_examples/applications/snells_law/index.html index 010d8a822..0872cd220 100644 --- a/generated_examples/applications/snells_law/index.html +++ b/generated_examples/applications/snells_law/index.html @@ -2813,7 +2813,7 @@

Snell's law demonstration using snells_law.show(run=True) -

Total running time of the script: ( 0 minutes 0.101 seconds)

+

Total running time of the script: ( 0 minutes 0.104 seconds)

Download Python source code: snells_law.py

diff --git a/generated_examples/applications/snells_law_codeobj.pickle b/generated_examples/applications/snells_law_codeobj.pickle index 4b4456724..ccb25a373 100644 Binary files a/generated_examples/applications/snells_law_codeobj.pickle and b/generated_examples/applications/snells_law_codeobj.pickle differ diff --git a/generated_examples/basic_example/index.html b/generated_examples/basic_example/index.html index 7906dec2f..c6e3386b7 100644 --- a/generated_examples/basic_example/index.html +++ b/generated_examples/basic_example/index.html @@ -2794,7 +2794,7 @@

Basic exampleexample.changed.connect(print) example.show(run=True) -

Total running time of the script: ( 0 minutes 1.469 seconds)

+

Total running time of the script: ( 0 minutes 1.622 seconds)

Download Python source code: basic_example.py

diff --git a/generated_examples/basic_widgets_demo/index.html b/generated_examples/basic_widgets_demo/index.html index b6a4b88e0..1eaec1ea7 100644 --- a/generated_examples/basic_widgets_demo/index.html +++ b/generated_examples/basic_widgets_demo/index.html @@ -2781,7 +2781,7 @@

Basic widgets demo

Out:

-
<MainFunctionGui widget_demo(boolean=True, integer=1, spin_float=3.14, slider_float=43.5, slider_int=550, string='Text goes here', dropdown=<Medium.Glass: 1.52>, radio_option=2, date=datetime.date(1999, 12, 31), time=datetime.time(1, 30, 20), datetime=datetime.datetime(2023, 10, 11, 11, 39, 57, 413000), filename=PosixPath('/Users/runner'))>
+
<MainFunctionGui widget_demo(boolean=True, integer=1, spin_float=3.14, slider_float=43.5, slider_int=550, string='Text goes here', dropdown=<Medium.Glass: 1.52>, radio_option=2, date=datetime.date(1999, 12, 31), time=datetime.time(1, 30, 20), datetime=datetime.datetime(2023, 10, 11, 20, 8, 39, 184000), filename=PosixPath('/Users/runner'))>
 


-

Total running time of the script: ( 0 minutes 0.283 seconds)

+

Total running time of the script: ( 0 minutes 0.296 seconds)

Download Python source code: basic_widgets_demo.py

diff --git a/generated_examples/basic_widgets_demo_codeobj.pickle b/generated_examples/basic_widgets_demo_codeobj.pickle index d849e9f01..4b93e92d5 100644 Binary files a/generated_examples/basic_widgets_demo_codeobj.pickle and b/generated_examples/basic_widgets_demo_codeobj.pickle differ diff --git a/generated_examples/demo_widgets/choices/index.html b/generated_examples/demo_widgets/choices/index.html index 1a3f1c697..64bde372b 100644 --- a/generated_examples/demo_widgets/choices/index.html +++ b/generated_examples/demo_widgets/choices/index.html @@ -2831,7 +2831,7 @@

Dropdown selection widget) container.show(run=True)

-

Total running time of the script: ( 0 minutes 0.104 seconds)

+

Total running time of the script: ( 0 minutes 0.113 seconds)

Download Python source code: choices.py

diff --git a/generated_examples/demo_widgets/choices_codeobj.pickle b/generated_examples/demo_widgets/choices_codeobj.pickle index af767567c..d37b4164f 100644 Binary files a/generated_examples/demo_widgets/choices_codeobj.pickle and b/generated_examples/demo_widgets/choices_codeobj.pickle differ diff --git a/generated_examples/demo_widgets/file_dialog/index.html b/generated_examples/demo_widgets/file_dialog/index.html index 7c7fde8d6..6779c7b34 100644 --- a/generated_examples/demo_widgets/file_dialog/index.html +++ b/generated_examples/demo_widgets/file_dialog/index.html @@ -2827,7 +2827,7 @@

File dialog widgetuse_app().run() -

Total running time of the script: ( 0 minutes 0.163 seconds)

+

Total running time of the script: ( 0 minutes 0.169 seconds)

Download Python source code: file_dialog.py

diff --git a/generated_examples/demo_widgets/file_dialog_codeobj.pickle b/generated_examples/demo_widgets/file_dialog_codeobj.pickle index 7ebec7f81..201fb1826 100644 Binary files a/generated_examples/demo_widgets/file_dialog_codeobj.pickle and b/generated_examples/demo_widgets/file_dialog_codeobj.pickle differ diff --git a/generated_examples/demo_widgets/image/index.html b/generated_examples/demo_widgets/image/index.html index 55e252b9b..583716596 100644 --- a/generated_examples/demo_widgets/image/index.html +++ b/generated_examples/demo_widgets/image/index.html @@ -2789,7 +2789,7 @@

Image widgetimage.scale_widget_to_image_size() image.show(run=True) -

Total running time of the script: ( 0 minutes 0.056 seconds)

+

Total running time of the script: ( 0 minutes 0.062 seconds)

Download Python source code: image.py

diff --git a/generated_examples/demo_widgets/image_codeobj.pickle b/generated_examples/demo_widgets/image_codeobj.pickle index 0ddd90b3a..6dd833665 100644 Binary files a/generated_examples/demo_widgets/image_codeobj.pickle and b/generated_examples/demo_widgets/image_codeobj.pickle differ diff --git a/generated_examples/demo_widgets/images/mkd_glr_file_dialog_001.png b/generated_examples/demo_widgets/images/mkd_glr_file_dialog_001.png index a39fe0703..4ab559828 100644 Binary files a/generated_examples/demo_widgets/images/mkd_glr_file_dialog_001.png and b/generated_examples/demo_widgets/images/mkd_glr_file_dialog_001.png differ diff --git a/generated_examples/demo_widgets/images/mkd_glr_file_dialog_002.png b/generated_examples/demo_widgets/images/mkd_glr_file_dialog_002.png index 65daa34a1..a39fe0703 100644 Binary files a/generated_examples/demo_widgets/images/mkd_glr_file_dialog_002.png and b/generated_examples/demo_widgets/images/mkd_glr_file_dialog_002.png differ diff --git a/generated_examples/demo_widgets/images/mkd_glr_file_dialog_003.png b/generated_examples/demo_widgets/images/mkd_glr_file_dialog_003.png index 4ab559828..65daa34a1 100644 Binary files a/generated_examples/demo_widgets/images/mkd_glr_file_dialog_003.png and b/generated_examples/demo_widgets/images/mkd_glr_file_dialog_003.png differ diff --git a/generated_examples/demo_widgets/images/thumb/mkd_glr_file_dialog_thumb.png b/generated_examples/demo_widgets/images/thumb/mkd_glr_file_dialog_thumb.png index a575c585d..0c7972afd 100644 Binary files a/generated_examples/demo_widgets/images/thumb/mkd_glr_file_dialog_thumb.png and b/generated_examples/demo_widgets/images/thumb/mkd_glr_file_dialog_thumb.png differ diff --git a/generated_examples/demo_widgets/log_slider/index.html b/generated_examples/demo_widgets/log_slider/index.html index 8de5f3f15..32db36c6e 100644 --- a/generated_examples/demo_widgets/log_slider/index.html +++ b/generated_examples/demo_widgets/log_slider/index.html @@ -2797,7 +2797,7 @@

Log slider widgetslider.show(run=True) -

Total running time of the script: ( 0 minutes 0.085 seconds)

+

Total running time of the script: ( 0 minutes 0.090 seconds)

Download Python source code: log_slider.py

diff --git a/generated_examples/demo_widgets/log_slider_codeobj.pickle b/generated_examples/demo_widgets/log_slider_codeobj.pickle index b1866f3ea..150d81411 100644 Binary files a/generated_examples/demo_widgets/log_slider_codeobj.pickle and b/generated_examples/demo_widgets/log_slider_codeobj.pickle differ diff --git a/generated_examples/demo_widgets/login/index.html b/generated_examples/demo_widgets/login/index.html index a36231ac1..d2958c3c4 100644 --- a/generated_examples/demo_widgets/login/index.html +++ b/generated_examples/demo_widgets/login/index.html @@ -2798,7 +2798,7 @@

Password loginlogin.show(run=True) -

Total running time of the script: ( 0 minutes 0.083 seconds)

+

Total running time of the script: ( 0 minutes 0.086 seconds)

Download Python source code: login.py

diff --git a/generated_examples/demo_widgets/mg_execution_times/index.html b/generated_examples/demo_widgets/mg_execution_times/index.html index 2d9c8eab1..54b85b693 100644 --- a/generated_examples/demo_widgets/mg_execution_times/index.html +++ b/generated_examples/demo_widgets/mg_execution_times/index.html @@ -2743,27 +2743,27 @@

Computation times#

-

00:00.976 total execution time for generated_examples_demo_widgets files:

+

00:01.021 total execution time for generated_examples_demo_widgets files:

+--------------------------------------------------------------------------------+-----------+--------+ -| file_dialog (docs/examples/demo_widgets/file_dialog.py) | 00:00.163 | 0.0 MB | +| file_dialog (docs/examples/demo_widgets/file_dialog.py) | 00:00.169 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| range_slider (docs/examples/demo_widgets/range_slider.py) | 00:00.149 | 0.0 MB | +| range_slider (docs/examples/demo_widgets/range_slider.py) | 00:00.155 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| choices (docs/examples/demo_widgets/choices.py) | 00:00.104 | 0.0 MB | +| choices (docs/examples/demo_widgets/choices.py) | 00:00.113 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| table (docs/examples/demo_widgets/table.py) | 00:00.093 | 0.0 MB | +| table (docs/examples/demo_widgets/table.py) | 00:00.098 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| selection (docs/examples/demo_widgets/selection.py) | 00:00.089 | 0.0 MB | +| selection (docs/examples/demo_widgets/selection.py) | 00:00.090 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| log_slider (docs/examples/demo_widgets/log_slider.py) | 00:00.085 | 0.0 MB | +| log_slider (docs/examples/demo_widgets/log_slider.py) | 00:00.090 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| login (docs/examples/demo_widgets/login.py) | 00:00.083 | 0.0 MB | +| login (docs/examples/demo_widgets/login.py) | 00:00.086 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | change_label (docs/examples/demo_widgets/change_label.py) | 00:00.082 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| optional (docs/examples/demo_widgets/optional.py) | 00:00.072 | 0.0 MB | +| optional (docs/examples/demo_widgets/optional.py) | 00:00.077 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ -| image (docs/examples/demo_widgets/image.py) | 00:00.056 | 0.0 MB | +| image (docs/examples/demo_widgets/image.py) | 00:00.062 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+

diff --git a/generated_examples/demo_widgets/optional/index.html b/generated_examples/demo_widgets/optional/index.html index 97208ed97..ef082cfcf 100644 --- a/generated_examples/demo_widgets/optional/index.html +++ b/generated_examples/demo_widgets/optional/index.html @@ -2796,7 +2796,7 @@

Optional user choicef.show(run=True) -

Total running time of the script: ( 0 minutes 0.072 seconds)

+

Total running time of the script: ( 0 minutes 0.077 seconds)

Download Python source code: optional.py

diff --git a/generated_examples/demo_widgets/optional_codeobj.pickle b/generated_examples/demo_widgets/optional_codeobj.pickle index 1ca2cdd0f..2895224a1 100644 Binary files a/generated_examples/demo_widgets/optional_codeobj.pickle and b/generated_examples/demo_widgets/optional_codeobj.pickle differ diff --git a/generated_examples/demo_widgets/range_slider/index.html b/generated_examples/demo_widgets/range_slider/index.html index 01a4f4aa7..7b2fa692e 100644 --- a/generated_examples/demo_widgets/range_slider/index.html +++ b/generated_examples/demo_widgets/range_slider/index.html @@ -2795,7 +2795,7 @@

Range slider widgetfunc.show(run=True) -

Total running time of the script: ( 0 minutes 0.149 seconds)

+

Total running time of the script: ( 0 minutes 0.155 seconds)

Download Python source code: range_slider.py

diff --git a/generated_examples/demo_widgets/range_slider_codeobj.pickle b/generated_examples/demo_widgets/range_slider_codeobj.pickle index 13f7a7074..945cdf1ae 100644 Binary files a/generated_examples/demo_widgets/range_slider_codeobj.pickle and b/generated_examples/demo_widgets/range_slider_codeobj.pickle differ diff --git a/generated_examples/demo_widgets/selection/index.html b/generated_examples/demo_widgets/selection/index.html index 2ed8aa2fe..3b0e9568f 100644 --- a/generated_examples/demo_widgets/selection/index.html +++ b/generated_examples/demo_widgets/selection/index.html @@ -2798,7 +2798,7 @@

Multiple selection widgetmy_widget.show(run=True) -

Total running time of the script: ( 0 minutes 0.089 seconds)

+

Total running time of the script: ( 0 minutes 0.090 seconds)

Download Python source code: selection.py

diff --git a/generated_examples/demo_widgets/table/index.html b/generated_examples/demo_widgets/table/index.html index cc6246ca9..7d071ab05 100644 --- a/generated_examples/demo_widgets/table/index.html +++ b/generated_examples/demo_widgets/table/index.html @@ -2779,7 +2779,7 @@

Table widgettable

Out:

-
Table(shape=(6, 3) at 0x13564cc90)
+
Table(shape=(6, 3) at 0x13a1b9b50)
 


-

Total running time of the script: ( 0 minutes 0.093 seconds)

+

Total running time of the script: ( 0 minutes 0.098 seconds)

Download Python source code: table.py

diff --git a/generated_examples/demo_widgets/table_codeobj.pickle b/generated_examples/demo_widgets/table_codeobj.pickle index 23d67aa04..e6132bad0 100644 Binary files a/generated_examples/demo_widgets/table_codeobj.pickle and b/generated_examples/demo_widgets/table_codeobj.pickle differ diff --git a/generated_examples/generated_examples_jupyter.zip b/generated_examples/generated_examples_jupyter.zip index 7fb2ad732..67fe69655 100644 Binary files a/generated_examples/generated_examples_jupyter.zip and b/generated_examples/generated_examples_jupyter.zip differ diff --git a/generated_examples/generated_examples_python.zip b/generated_examples/generated_examples_python.zip index ac76977be..7f86322cf 100644 Binary files a/generated_examples/generated_examples_python.zip and b/generated_examples/generated_examples_python.zip differ diff --git a/generated_examples/images/mkd_glr_basic_widgets_demo_001.png b/generated_examples/images/mkd_glr_basic_widgets_demo_001.png index 8017d0e4f..49a135489 100644 Binary files a/generated_examples/images/mkd_glr_basic_widgets_demo_001.png and b/generated_examples/images/mkd_glr_basic_widgets_demo_001.png differ diff --git a/generated_examples/images/thumb/mkd_glr_basic_widgets_demo_thumb.png b/generated_examples/images/thumb/mkd_glr_basic_widgets_demo_thumb.png index 4952c8395..bb1f18c26 100644 Binary files a/generated_examples/images/thumb/mkd_glr_basic_widgets_demo_thumb.png and b/generated_examples/images/thumb/mkd_glr_basic_widgets_demo_thumb.png differ diff --git a/generated_examples/matplotlib/mg_execution_times/index.html b/generated_examples/matplotlib/mg_execution_times/index.html index 7c3047b9e..4a846cc2d 100644 --- a/generated_examples/matplotlib/mg_execution_times/index.html +++ b/generated_examples/matplotlib/mg_execution_times/index.html @@ -2743,11 +2743,11 @@

Computation times#

-

00:00.814 total execution time for generated_examples_matplotlib files:

+

00:00.920 total execution time for generated_examples_matplotlib files:

+------------------------------------------------------------------------+-----------+--------+ -| waveform (docs/examples/matplotlib/waveform.py) | 00:00.522 | 0.0 MB | +| waveform (docs/examples/matplotlib/waveform.py) | 00:00.562 | 0.0 MB | +------------------------------------------------------------------------+-----------+--------+ -| mpl_figure (docs/examples/matplotlib/mpl_figure.py) | 00:00.292 | 0.0 MB | +| mpl_figure (docs/examples/matplotlib/mpl_figure.py) | 00:00.359 | 0.0 MB | +------------------------------------------------------------------------+-----------+--------+

diff --git a/generated_examples/matplotlib/mpl_figure/index.html b/generated_examples/matplotlib/mpl_figure/index.html index adfbba995..f18e6a76e 100644 --- a/generated_examples/matplotlib/mpl_figure/index.html +++ b/generated_examples/matplotlib/mpl_figure/index.html @@ -2812,7 +2812,7 @@

matplotlib figure examplef.show(run=True)

-

Total running time of the script: ( 0 minutes 0.292 seconds)

+

Total running time of the script: ( 0 minutes 0.359 seconds)

Download Python source code: mpl_figure.py

diff --git a/generated_examples/matplotlib/mpl_figure_codeobj.pickle b/generated_examples/matplotlib/mpl_figure_codeobj.pickle index c70342151..fef843c85 100644 Binary files a/generated_examples/matplotlib/mpl_figure_codeobj.pickle and b/generated_examples/matplotlib/mpl_figure_codeobj.pickle differ diff --git a/generated_examples/matplotlib/waveform/index.html b/generated_examples/matplotlib/waveform/index.html index e025ed7aa..7cc446f51 100644 --- a/generated_examples/matplotlib/waveform/index.html +++ b/generated_examples/matplotlib/waveform/index.html @@ -3013,7 +3013,7 @@

Waveforms examplewaveform = WaveForm() waveform.show(run=True) -

Total running time of the script: ( 0 minutes 0.522 seconds)

+

Total running time of the script: ( 0 minutes 0.562 seconds)

Download Python source code: waveform.py

diff --git a/generated_examples/matplotlib/waveform_codeobj.pickle b/generated_examples/matplotlib/waveform_codeobj.pickle index 780937ee3..719cf77c3 100644 Binary files a/generated_examples/matplotlib/waveform_codeobj.pickle and b/generated_examples/matplotlib/waveform_codeobj.pickle differ diff --git a/generated_examples/mg_execution_times/index.html b/generated_examples/mg_execution_times/index.html index 96c157094..7a27432f2 100644 --- a/generated_examples/mg_execution_times/index.html +++ b/generated_examples/mg_execution_times/index.html @@ -2743,11 +2743,11 @@

Computation times#

-

00:01.752 total execution time for generated_examples files:

+

00:01.918 total execution time for generated_examples files:

+-------------------------------------------------------------------------------------+-----------+--------+ -| basic_example (docs/examples/basic_example.py) | 00:01.469 | 0.0 MB | +| basic_example (docs/examples/basic_example.py) | 00:01.622 | 0.0 MB | +-------------------------------------------------------------------------------------+-----------+--------+ -| basic_widgets_demo (docs/examples/basic_widgets_demo.py) | 00:00.283 | 0.0 MB | +| basic_widgets_demo (docs/examples/basic_widgets_demo.py) | 00:00.296 | 0.0 MB | +-------------------------------------------------------------------------------------+-----------+--------+

diff --git a/generated_examples/napari/images/mkd_glr_napari_img_math_001.png b/generated_examples/napari/images/mkd_glr_napari_img_math_001.png index af5d3faf2..07754e534 100644 Binary files a/generated_examples/napari/images/mkd_glr_napari_img_math_001.png and b/generated_examples/napari/images/mkd_glr_napari_img_math_001.png differ diff --git a/generated_examples/napari/images/thumb/mkd_glr_napari_img_math_thumb.png b/generated_examples/napari/images/thumb/mkd_glr_napari_img_math_thumb.png index 7a9a5d606..771246835 100644 Binary files a/generated_examples/napari/images/thumb/mkd_glr_napari_img_math_thumb.png and b/generated_examples/napari/images/thumb/mkd_glr_napari_img_math_thumb.png differ diff --git a/generated_examples/napari/mg_execution_times/index.html b/generated_examples/napari/mg_execution_times/index.html index c8a244e6e..b8304ef51 100644 --- a/generated_examples/napari/mg_execution_times/index.html +++ b/generated_examples/napari/mg_execution_times/index.html @@ -2743,15 +2743,15 @@

Computation times#

-

00:29.257 total execution time for generated_examples_napari files:

+

00:25.609 total execution time for generated_examples_napari files:

+--------------------------------------------------------------------------------------------------------+-----------+--------+ -| napari_combine_qt (docs/examples/napari/napari_combine_qt.py) | 00:19.594 | 0.0 MB | +| napari_combine_qt (docs/examples/napari/napari_combine_qt.py) | 00:17.132 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ -| napari_parameter_sweep (docs/examples/napari/napari_parameter_sweep.py) | 00:05.948 | 0.0 MB | +| napari_parameter_sweep (docs/examples/napari/napari_parameter_sweep.py) | 00:04.880 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ -| napari_img_math (docs/examples/napari/napari_img_math.py) | 00:03.612 | 0.0 MB | +| napari_img_math (docs/examples/napari/napari_img_math.py) | 00:03.485 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ -| napari_forward_refs (docs/examples/napari/napari_forward_refs.py) | 00:00.102 | 0.0 MB | +| napari_forward_refs (docs/examples/napari/napari_forward_refs.py) | 00:00.112 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+

diff --git a/generated_examples/napari/napari_combine_qt/index.html b/generated_examples/napari/napari_combine_qt/index.html index cc48174c9..43c65ad08 100644 --- a/generated_examples/napari/napari_combine_qt/index.html +++ b/generated_examples/napari/napari_combine_qt/index.html @@ -2825,7 +2825,7 @@

napari Qt demonapari.run() -

Total running time of the script: ( 0 minutes 19.594 seconds)

+

Total running time of the script: ( 0 minutes 17.132 seconds)

Download Python source code: napari_combine_qt.py

diff --git a/generated_examples/napari/napari_combine_qt_codeobj.pickle b/generated_examples/napari/napari_combine_qt_codeobj.pickle index abc8c5731..db7e1fa9c 100644 Binary files a/generated_examples/napari/napari_combine_qt_codeobj.pickle and b/generated_examples/napari/napari_combine_qt_codeobj.pickle differ diff --git a/generated_examples/napari/napari_forward_refs/index.html b/generated_examples/napari/napari_forward_refs/index.html index 0ad70c1d7..0f2f6c4a4 100644 --- a/generated_examples/napari/napari_forward_refs/index.html +++ b/generated_examples/napari/napari_forward_refs/index.html @@ -2814,7 +2814,7 @@

napari forward reference demo# you could add this widget to a napari viewer with # viewer.window.add_dock_widget(subtract_background) -

Total running time of the script: ( 0 minutes 0.102 seconds)

+

Total running time of the script: ( 0 minutes 0.112 seconds)

Download Python source code: napari_forward_refs.py

diff --git a/generated_examples/napari/napari_forward_refs_codeobj.pickle b/generated_examples/napari/napari_forward_refs_codeobj.pickle index 867714001..507e87ef7 100644 Binary files a/generated_examples/napari/napari_forward_refs_codeobj.pickle and b/generated_examples/napari/napari_forward_refs_codeobj.pickle differ diff --git a/generated_examples/napari/napari_img_math/index.html b/generated_examples/napari/napari_img_math/index.html index 65c22858d..1cf83fa38 100644 --- a/generated_examples/napari/napari_img_math/index.html +++ b/generated_examples/napari/napari_img_math/index.html @@ -3228,7 +3228,7 @@

Code napari.run() -

Total running time of the script: ( 0 minutes 3.612 seconds)

+

Total running time of the script: ( 0 minutes 3.485 seconds)

Download Python source code: napari_img_math.py

diff --git a/generated_examples/napari/napari_img_math_codeobj.pickle b/generated_examples/napari/napari_img_math_codeobj.pickle index b03e0fd52..f9000becd 100644 Binary files a/generated_examples/napari/napari_img_math_codeobj.pickle and b/generated_examples/napari/napari_img_math_codeobj.pickle differ diff --git a/generated_examples/napari/napari_parameter_sweep/index.html b/generated_examples/napari/napari_parameter_sweep/index.html index 455803715..ff87e2f08 100644 --- a/generated_examples/napari/napari_parameter_sweep/index.html +++ b/generated_examples/napari/napari_parameter_sweep/index.html @@ -3167,7 +3167,7 @@

Code napari.run() -

Total running time of the script: ( 0 minutes 5.948 seconds)

+

Total running time of the script: ( 0 minutes 4.880 seconds)

Download Python source code: napari_parameter_sweep.py

diff --git a/generated_examples/napari/napari_parameter_sweep_codeobj.pickle b/generated_examples/napari/napari_parameter_sweep_codeobj.pickle index acd88c265..6a5abe755 100644 Binary files a/generated_examples/napari/napari_parameter_sweep_codeobj.pickle and b/generated_examples/napari/napari_parameter_sweep_codeobj.pickle differ diff --git a/generated_examples/progress_bars/mg_execution_times/index.html b/generated_examples/progress_bars/mg_execution_times/index.html index 6ef15a2e4..0946abac2 100644 --- a/generated_examples/progress_bars/mg_execution_times/index.html +++ b/generated_examples/progress_bars/mg_execution_times/index.html @@ -2743,15 +2743,15 @@

Computation times#

-

00:00.302 total execution time for generated_examples_progress_bars files:

+

00:00.303 total execution time for generated_examples_progress_bars files:

+---------------------------------------------------------------------------------------------------------------+-----------+--------+ -| progress_nested (docs/examples/progress_bars/progress_nested.py) | 00:00.097 | 0.0 MB | +| progress_nested (docs/examples/progress_bars/progress_nested.py) | 00:00.101 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ -| progress_manual (docs/examples/progress_bars/progress_manual.py) | 00:00.075 | 0.0 MB | +| progress_manual (docs/examples/progress_bars/progress_manual.py) | 00:00.077 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ -| progress (docs/examples/progress_bars/progress.py) | 00:00.068 | 0.0 MB | +| progress (docs/examples/progress_bars/progress.py) | 00:00.072 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ -| progress_indeterminate (docs/examples/progress_bars/progress_indeterminate.py) | 00:00.062 | 0.0 MB | +| progress_indeterminate (docs/examples/progress_bars/progress_indeterminate.py) | 00:00.053 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+

diff --git a/generated_examples/progress_bars/progress/index.html b/generated_examples/progress_bars/progress/index.html index 7a570800f..c57f1f651 100644 --- a/generated_examples/progress_bars/progress/index.html +++ b/generated_examples/progress_bars/progress/index.html @@ -2803,7 +2803,7 @@

Simple progress barlong_running.show(run=True) -

Total running time of the script: ( 0 minutes 0.068 seconds)

+

Total running time of the script: ( 0 minutes 0.072 seconds)

Download Python source code: progress.py

diff --git a/generated_examples/progress_bars/progress_codeobj.pickle b/generated_examples/progress_bars/progress_codeobj.pickle index 2d9778427..7d5f88a61 100644 Binary files a/generated_examples/progress_bars/progress_codeobj.pickle and b/generated_examples/progress_bars/progress_codeobj.pickle differ diff --git a/generated_examples/progress_bars/progress_indeterminate/index.html b/generated_examples/progress_bars/progress_indeterminate/index.html index 8b3408962..68510416d 100644 --- a/generated_examples/progress_bars/progress_indeterminate/index.html +++ b/generated_examples/progress_bars/progress_indeterminate/index.html @@ -2809,7 +2809,7 @@

Indeterminate progress barlong_running.show(run=True) -

Total running time of the script: ( 0 minutes 0.062 seconds)

+

Total running time of the script: ( 0 minutes 0.053 seconds)

Download Python source code: progress_indeterminate.py

diff --git a/generated_examples/progress_bars/progress_indeterminate_codeobj.pickle b/generated_examples/progress_bars/progress_indeterminate_codeobj.pickle index 32af579f7..ac1b88912 100644 Binary files a/generated_examples/progress_bars/progress_indeterminate_codeobj.pickle and b/generated_examples/progress_bars/progress_indeterminate_codeobj.pickle differ diff --git a/generated_examples/progress_bars/progress_manual/index.html b/generated_examples/progress_bars/progress_manual/index.html index 660a3f950..6dd158ba5 100644 --- a/generated_examples/progress_bars/progress_manual/index.html +++ b/generated_examples/progress_bars/progress_manual/index.html @@ -2779,7 +2779,7 @@

Manual progress bar

Out:

-
<FunctionGui manual(pbar: magicgui.widgets.ProgressBar = ProgressBar(value=<function match_type.<locals>.<lambda> at 0x13e3f9940>, annotation=<class 'magicgui.widgets.ProgressBar'>, name='pbar'), increment: bool = 1)>
+
<FunctionGui manual(pbar: magicgui.widgets.ProgressBar = ProgressBar(value=<function match_type.<locals>.<lambda> at 0x142b1b6a0>, annotation=<class 'magicgui.widgets.ProgressBar'>, name='pbar'), increment: bool = 1)>
 


-

Total running time of the script: ( 0 minutes 0.075 seconds)

+

Total running time of the script: ( 0 minutes 0.077 seconds)

Download Python source code: progress_manual.py

diff --git a/generated_examples/progress_bars/progress_manual_codeobj.pickle b/generated_examples/progress_bars/progress_manual_codeobj.pickle index 818c52d30..9a6663fe6 100644 Binary files a/generated_examples/progress_bars/progress_manual_codeobj.pickle and b/generated_examples/progress_bars/progress_manual_codeobj.pickle differ diff --git a/generated_examples/progress_bars/progress_nested/index.html b/generated_examples/progress_bars/progress_nested/index.html index 21afdec5d..d83820f4c 100644 --- a/generated_examples/progress_bars/progress_nested/index.html +++ b/generated_examples/progress_bars/progress_nested/index.html @@ -2812,7 +2812,7 @@

Nested progress barslong_function.show(run=True)

-

Total running time of the script: ( 0 minutes 0.097 seconds)

+

Total running time of the script: ( 0 minutes 0.101 seconds)

Download Python source code: progress_nested.py

diff --git a/generated_examples/progress_bars/progress_nested_codeobj.pickle b/generated_examples/progress_bars/progress_nested_codeobj.pickle index b5dec3f22..86fcf221a 100644 Binary files a/generated_examples/progress_bars/progress_nested_codeobj.pickle and b/generated_examples/progress_bars/progress_nested_codeobj.pickle differ diff --git a/generated_examples/under_the_hood/class_method/index.html b/generated_examples/under_the_hood/class_method/index.html index add2504f2..5f0062f66 100644 --- a/generated_examples/under_the_hood/class_method/index.html +++ b/generated_examples/under_the_hood/class_method/index.html @@ -2813,7 +2813,7 @@

Deocrate class methods with magicg assert a.method() == "a" assert b.method() == "b" -

Total running time of the script: ( 0 minutes 0.050 seconds)

+

Total running time of the script: ( 0 minutes 0.056 seconds)

Download Python source code: class_method.py

diff --git a/generated_examples/under_the_hood/class_method_codeobj.pickle b/generated_examples/under_the_hood/class_method_codeobj.pickle index 2150fb0d0..a8944eb9c 100644 Binary files a/generated_examples/under_the_hood/class_method_codeobj.pickle and b/generated_examples/under_the_hood/class_method_codeobj.pickle differ diff --git a/generated_examples/under_the_hood/mg_execution_times/index.html b/generated_examples/under_the_hood/mg_execution_times/index.html index 996060a10..52378c474 100644 --- a/generated_examples/under_the_hood/mg_execution_times/index.html +++ b/generated_examples/under_the_hood/mg_execution_times/index.html @@ -2743,11 +2743,11 @@

Computation times#

-

00:00.111 total execution time for generated_examples_under_the_hood files:

+

00:00.120 total execution time for generated_examples_under_the_hood files:

+----------------------------------------------------------------------------------------+-----------+--------+ -| self_reference (docs/examples/under_the_hood/self_reference.py) | 00:00.061 | 0.0 MB | +| self_reference (docs/examples/under_the_hood/self_reference.py) | 00:00.064 | 0.0 MB | +----------------------------------------------------------------------------------------+-----------+--------+ -| class_method (docs/examples/under_the_hood/class_method.py) | 00:00.050 | 0.0 MB | +| class_method (docs/examples/under_the_hood/class_method.py) | 00:00.056 | 0.0 MB | +----------------------------------------------------------------------------------------+-----------+--------+

diff --git a/generated_examples/under_the_hood/self_reference/index.html b/generated_examples/under_the_hood/self_reference/index.html index 1e4de46b9..f4ae5fad0 100644 --- a/generated_examples/under_the_hood/self_reference/index.html +++ b/generated_examples/under_the_hood/self_reference/index.html @@ -2794,7 +2794,7 @@

Self reference magicgui widgetsfunction.show(run=True) -

Total running time of the script: ( 0 minutes 0.061 seconds)

+

Total running time of the script: ( 0 minutes 0.064 seconds)

Download Python source code: self_reference.py

diff --git a/generated_examples/under_the_hood/self_reference_codeobj.pickle b/generated_examples/under_the_hood/self_reference_codeobj.pickle index 8b54be621..07454b516 100644 Binary files a/generated_examples/under_the_hood/self_reference_codeobj.pickle and b/generated_examples/under_the_hood/self_reference_codeobj.pickle differ diff --git a/scripts/__pycache__/_hooks.cpython-311.pyc b/scripts/__pycache__/_hooks.cpython-311.pyc index 8c4cc6aaa..462c6d769 100644 Binary files a/scripts/__pycache__/_hooks.cpython-311.pyc and b/scripts/__pycache__/_hooks.cpython-311.pyc differ diff --git a/search/search_index.json b/search/search_index.json index 5bdac78bc..d83f3e771 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"magicgui \ud83e\uddd9","text":"

magicgui is a python library for building graphical user interfaces (GUIs).

It aims to speed up data workflows by providing a simple, consistent API for creating GUIs to control various data types, that work across various environments.

GUIs may be built manually using a variety of widgets, or generated automatically from python type hints.

"},{"location":"#magicgui-organization","title":"magicgui organization","text":"

magicgui can be thought of as performing two distinct tasks:

  1. Providing an simplified abstraction layer for GUI frameworks, allowing you to use the same API to create UIs that can move between environments and frameworks (such as a desktop app, or a Jupyter notebook).
  2. Providing a mapping of python types to widgets, allowing you to autogenerate graphical user interfaces for functions and dataclasses by annotating with standard python type hints.

While there is some degree of customizeability, the emphasis is on rapid development of relatively simple GUIs, with minimal boilerplate. For highly customized GUIs with complex layouts, it may be more appropriate to use a lower-level GUI framework.

The API is organized into 2 main levels:

magicgui API layers"},{"location":"#python-type-mapping","title":"Python Type Mapping","text":"

At its highest level, magicgui provides a mapping of Python types to widgets. This API allows you to create graphical user interfaces for your functions and dataclasses simply by annotating them with standard python type hints.

Type hints??

Type hints are a way to annotate your code with information about the types of variables and function arguments. They are completely optional, but static type checkers and other libraries (like magicgui!) can use them to check your code and/or provide additional functionality.

Typically, they are provided after a colon following a variable name or function argument.

In the example below, param_a has been annotated as an int, param_b as a str, and the return value as a list.

def my_function(param_a: int, param_b: str) -> list:\n    ...\n

If you are new to type annotations in Python, here are a few resources to get you started:

"},{"location":"#create_widget","title":"create_widget","text":"

magicgui.widgets.create_widget is a general function, used throughout the library, that allows you to create a widget for a specific Python type or value:

from magicgui.widgets import create_widget\n\n# passing a type to create_widget\nwidget = create_widget(annotation=int)\nwidget.show()\n

# passing a value to create_widget\nwidget2 = create_widget(value=\"Hello World\")\nwidget2.show()\n

For more details on how magicgui maps types to widgets, see Type Mapping.

"},{"location":"#magicgui_1","title":"magicgui","text":"

The magicgui.magicgui function is one way to autogenerate a compound Widget based on the parameters of a function:

from typing import Annotated, Literal\n# for Python <= 3.8\n# from typing_extensions import Annotated\n# for Python <= 3.7\n# from typing_extensions import Annotated, Literal\n\nfrom magicgui import magicgui\n\n\n@magicgui\ndef my_function(\n    param_a: int,\n    param_b: Annotated[int, {'widget_type': \"Slider\", 'max': 100}] = 42,\n    param_c: Literal[\"First\", \"Second\", \"Third\"] = \"Second\"\n):\n    print(\"param_a:\", param_a)\n    print(\"param_b:\", param_b)\n    print(\"param_c:\", param_c)\n\n# my_function now IS a widget, in addition to being a callable function\nmy_function.show()\n

For more details on using magicgui and magic_factory, see the magicgui decorators page.

"},{"location":"#guiclass","title":"guiclass","text":"

magicgui.experimental.guiclass is a newer experimental feature that provides an object-oriented alternative to magicgui. It wraps dataclasses.dataclass and adds a gui attribute to the resulting class, which is a magicgui-generated widget that can be used to control the dataclass instance. (The widget is only created when the gui attribute is accessed for the first time.)

from magicgui.experimental import guiclass, button\n\n@guiclass\nclass MyDataclass:\n    a: int = 0\n    b: str = 'hello'\n    c: bool = True\n\n    @button\n    def compute(self):\n        print(self.a, self.b, self.c)\n\nobj = MyDataclass(a=10, b='foo')\nobj.gui.show()\n

For more details on using the guiclass decorator, see Dataclasses & guiclass.

"},{"location":"#widgets","title":"Widgets","text":"

At the lower level, magicgui is a library of widgets (the individual elements that make up a graphical user interface). Each widget is customized to display and interact with a specific type of data. In some cases, it makes more sense to create and arrange these widgets manually, rather than using the type-based autogeneration features described above.

Magicgui acts as an abstraction layer for a variety of different GUI toolkits, allowing you to use the same API to create UIs that can move between environments (such as a desktop app, or a Jupyter notebook).

Currently, magicgui supports the following backends:

You can use magicgui.widgets to quickly build graphical user interfaces.

from magicgui import widgets\n\na = widgets.SpinBox(value=10, label=\"a\")\nb = widgets.Slider(value=20, min=0, max=100, label=\"b\")\nresult = widgets.LineEdit(value=a.value * b.value, label=\"result\")\nbutton = widgets.PushButton(text=\"multiply\")\n\n@button.clicked.connect\ndef on_button_click():\n    result.value = a.value * b.value\n\ncontainer = widgets.Container(widgets=[a, b, result, button])\ncontainer.show()\n

To learn more about the available widgets and how to use them, see the Widgets Overview.

...details

Behind the scenes, magicgui declares a set of WidgetProtocols that each backend must implement, and every magicgui Widget is a wrapper around a backend-specific widget. Most users will never need to worry about this, but it's good to know that it's there if you ever need to dig deeper.

"},{"location":"#events","title":"Events","text":"

All widgets (whether created directly or autogenerated based on type hints) emit events when their value changes or in response to interaction.

To learn about connecting custom functionality to these events, see Events.

"},{"location":"#installation","title":"Installation","text":"

See installing magicgui.

"},{"location":"CONTRIBUTING/","title":"Contributing","text":"

Contributions are welcome!

"},{"location":"CONTRIBUTING/#development","title":"Development","text":"

To install magicgui for development, first clone the repository:

git clone https://github.com/pyapp-kit/magicgui\ncd magicgui\n

Then install the package in editable mode with the dev extra:

pip install -e .[dev]\n

To run the tests:

pytest\n
"},{"location":"CONTRIBUTING/#code-quality","title":"Code Quality","text":"

magicgui attempts to adhere to strict coding rules and employs the following static analysis tools to prevent errors from being introduced into the codebase:

To prevent continuous integration failures when contributing, please consider installing pre-commit in your environment to run all of these checks prior to checking in new code.

pre-commit install\n

To run the checks manually, you can use:

pre-commit run --all-files\n
"},{"location":"CONTRIBUTING/#adding-a-widget","title":"Adding a widget","text":"

These instructions may change in the future as the repo structures changes. If they appear outdated as you follow them, please open an issue.

To add a new widget, you will need to:

  1. Create a new class in magicgui/widgets/_concrete.py that inherits from the base class most appropriate for your widget (e.g. ValueWidget, or CategoricalWidget).

    In some (complex) cases, you may need to extend one of the base classes. If so, it is likely that you will also need to extend one of the Protocols found in magicgui.widgets.protocols. This is where all of protocols that backend classes need to implement to work with a given widget type. (Don't hesitate to open an issue if you're confused).

  2. Most likely, you will want to decorate the class with @backend_widget. Using this decorator implies that there is a class with the same name in any any backend modules that will support this widget type (e.g. magicgui.backends._qtpy.widgets for Qt support.).

  3. Make any changes necessary to your new concrete class. For example, you may need to change the value property and corresponding setter to handle a specific type. This part of the code should be backend agnostic.
  4. Export the new class in magicgui/widgets/__init__.py so that it can be imported from magicgui.widgets.
  5. Implement the backend widget class (using the same class name) in the appropriate backend module (e.g. magicgui.backends._qtpy.widgets for Qt support). Usually this will mean implementing the appropriate _mgui_get/set_... methods for the Protocol of the corresponding widget base class your chose to extend.
  6. Export the backend widget class in the __init__.py of the backend module (e.g. magicgui.backends._qtpy.__init__.py for Qt support). This is important, as that is where the @backend_widget decorator will look.
  7. Add a test for your new widget.

For an example of a minimal PR adding a new widget, see #483, which added a QuantityWidget to be used with pint.Quantity objects.

"},{"location":"CONTRIBUTING/#associating-a-widget-with-a-type","title":"Associating a widget with a type","text":"

To associate your new widget with a specific type such that it will be used when someone annotates a parameter with that type, you will need to update code in magicgui.type_map._type_map.

In the simplest of cases, this will mean adding a new entry to the magicgui.type_map._type_map._SIMPLE_TYPES dict. This is a mapping from a python type to a widget class. (Note that all subclasses of the type will also be matched.)

For more complex cases, you can add a new conditional to the body of the match_type function. That function should always return a tuple of widget type, and kwargs that will be passed to the widget constructor. For example: return widgets.MyNewWidget, {}.

"},{"location":"CONTRIBUTING/#building-the-documentation","title":"Building the documentation","text":"

To build the documentation locally, you will need to install the docs extra:

pip install -e .[docs]\n

Then, from the root of the repository, run:

mkdocs serve\n

This will start a local server at http://127.0.0.1:8000/ where you can view the documentation as you edit it.

"},{"location":"dataclasses/","title":"Dataclasses & guiclass","text":""},{"location":"dataclasses/#what-are-dataclasses","title":"What are dataclasses?","text":"

dataclasses are a feature added in Python 3.7 (PEP 557) that allow you to simply define classes that store a specific set of data. They encourage clear, type-annotated code, and are a great way to define data structures with minimal boilerplate.

New to dataclasses?

If you're totally new to dataclasses, you might want to start with the official documentation for the dataclasses module, or this Real Python post on dataclasses. The following is a very brief example of the key features:

Example dataclass
from dataclasses import dataclass\n\n@dataclass  # (1)!\nclass Person:\n    name: str # (2)!\n    age: int = 0  # (3)!\n\np = Person(name='John', age=30)  # (4)!\nprint(p) # (5)!\n
  1. The @dataclass decorator is used to mark a class as a dataclass. This will automatically generate an __init__ method with a parameter for each annotated class attribute.
  2. Attribute names are annotated with types. Note that, as with all Python type hints, these have no runtime effect (i.e. no validation is performed).
  3. Optional attributes can be defined with a default value. If no default value is specified, then the field is required when creating a new object.
  4. Creating a new object is as simple as passing in the required arguments.
  5. The __repr__ method is automatically generated and will print out the class name and all of the attributes and their current values.
"},{"location":"dataclasses/#dataclass-patterns-outside-the-standard-library","title":"dataclass patterns outside the standard library","text":"

The dataclasses module is not the only way to define data-focused classes in Python. There are other libraries that provide similar functionality, and some of them have additional features that are not available in the standard library.

"},{"location":"dataclasses/#magicgui-guiclass","title":"magicgui guiclass","text":"

Experimental

This is an experimental feature. The API may change in the future without deprecations or warnings.

magicgui supports the dataclass API as a way to define the interface for compound widget, where each attribute of the dataclass is a separate widget. The magicgui.experimental.guiclass decorator can be used to mark a class as a \"GUI class\". A GUI class is a Python standard dataclass that has two additional features:

  1. A property (named \"gui\" by default) that returns a Container widget which contains a widget for each attribute of the dataclass.
  2. An property (named \"events\" by default) that returns a psygnal.SignalGroup object that allows you to connect callbacks to the change event of any of field in the dataclass. (Under the hood, this uses the @evented dataclass decorator from psygnal.)

Tip

You can still use all of the standard dataclass features, including field values, __post_init__ processing, and ClassVar.

Info

In the future, we may also support other dataclass-like objects, such as pydantic models, attrs classes, and traitlets classes.

from magicgui.experimental import guiclass\n\n@guiclass\nclass MyDataclass:\n    a: int = 0\n    b: str = 'hello'\n    c: bool = True\n\nobj = MyDataclass()\nobj.gui.show()\n

The individual widgets in the Container may be accessed by the same name as the corresponding attribute. For example, obj.gui.a will return the SpinBox widget that controls the value of the a attribute.

"},{"location":"dataclasses/#two-way-data-binding","title":"Two-way data binding","text":"

As you interact programmatically with the obj instance, the widgets in the obj.gui will update. Similarly, as you change the value of the widgets in the obj.gui, the values of the obj instance will be updated.

obj = MyDataclass(a=10)\nobj.b = 'world'\nobj.c = False\n\nobj.gui.show()\n

All magicgui-related stuff is in the gui attribute

The original dataclass instance (obj) is essentially untouched. Just as in a regular dataclass, obj.a returns the current value of a in the dataclass. The widget for the class will be at obj.gui (or whatever name you specified in the gui_name parameter) So, obj.gui.a.value, returns the current value of the widget. Unless you explicitly disconnect the gui from the underlying object/model, the two will always be in sync.

"},{"location":"dataclasses/#adding-buttons-and-callbacks","title":"Adding buttons and callbacks","text":"

Buttons are one of the few widget types that tend not to have an associated value, but simply trigger a callback when clicked. That is: it doesn't often make sense to add a field to a dataclass representing a button. To add a button to a guiclass, decorate a method with the magicgui.experimental.button decorator.

positioning buttons

Currently, all buttons are appended to the end of the widget. The ability to position the button in the layout will be added in the future.

Any additional keyword arguments to the button decorator will be passed to the magicgui.widgets.PushButton constructor (e.g. label, tooltip, etc.)

from magicgui.experimental import guiclass, button\n\n@guiclass\nclass Greeter:\n    first_name: str\n\n    @button\n    def say_hello(self):\n        print(f'Hello {self.first_name}')\n\ngreeter = Greeter('Talley')\ngreeter.gui.show()\n

clicking the \"say_hello\" button will print \"Hello Talley\" to the console

Tip

As your widget begins to manage more internal state, the guiclass pattern becomes much more useful than the magicgui decorator pattern -- which was designed with pure functions that take inputs and return outputs in mind.

"},{"location":"decorators/","title":"magicgui & magic_factory","text":""},{"location":"decorators/#from-object-to-gui","title":"From Object to GUI","text":"

The eponymous feature of magicgui is the magicgui.magicgui function, which converts an object into a widget.

Info

Currently, the only supported objects are functions, but in the future magicgui.magicgui may accept other objects, such as dataclass instances

When used to decorate a function, @magicgui will autogenerate a graphical user interface (GUI) by inspecting the function signature and adding an appropriate GUI widget for each parameter, as described in Type Hints to Widgets. Parameter types are taken from type hints, if provided, or inferred using the type of the default value otherwise.

import math\nfrom enum import Enum\nfrom magicgui import magicgui\n\n# dropdown boxes are best made by creating an enum\nclass Medium(Enum):\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n# decorate your function with the @magicgui decorator\n@magicgui(call_button=\"calculate\")\ndef snells_law(aoi=30.0, n1=Medium.Glass, n2=Medium.Water, degrees=True):\n    aoi = math.radians(aoi) if degrees else aoi\n    try:\n        result = math.asin(n1.value * math.sin(aoi) / n2.value)\n        return math.degrees(result) if degrees else result\n    except ValueError:\n        # beyond the critical angle\n        return \"Total internal reflection!\"\n\nsnells_law.show()\n

The object returned by the magicgui decorator is an instance of magicgui.widgets.FunctionGui. It can still be called like the original function, but it also knows how to present itself as a GUI.

"},{"location":"decorators/#two-way-data-binding","title":"Two-Way Data Binding","text":"

The modified snells_law object gains attributes named after each of the parameters in the function. Each attribute is an instance of a magicgui.widgets.Widget subclass (suitable for the data type represented by that parameter). As you make changes in your GUI, the attributes of the snells_law object will be kept in sync. For instance, change the first dropdown menu from \"Glass\" to \"Oil\", and the corresponding n1 object on snells_law will change its value to 1.515:

snells_law.n1.value  # 1.515\n

It goes both ways: set a parameter in the console and it will change in the GUI:

snells_law.aoi.value = 47\nsnells_law.show()\n

"},{"location":"decorators/#its-still-a-function","title":"It's still a function","text":"

magicgui tries very hard to make it so that the decorated object behaves as much like the original object as possible.

We can invoke the function in a few ways:

"},{"location":"decorators/#connecting-events","title":"Connecting Events","text":""},{"location":"decorators/#function-calls","title":"Function Calls","text":"

With a GUI, you are usually looking for something to happen as a result of calling the function. The function will have a new called attribute that you can connect to an arbitrary callback function:

@snells_law.called.connect\ndef my_callback(value: str):\n    # The callback receives an `Event` object that has the result\n    # of the function call in the `value` attribute\n    print(f\"Your function was called! The result is: {value}\")\n\nresult = snells_law()\n

Now when you call snells_law(), or click the calculate button in the gui, my_callback will be called with the result of the calculation.

"},{"location":"decorators/#parameter-changes","title":"Parameter Changes","text":"

You can also listen for changes on individual function parameters by connecting to the <parameter_name>.changed signal:

# whenever the current value for n1 changes, print it to the console:\n@snells_law.n1.changed.connect\ndef _on_n1_changed(x: Medium):\n    print(f\"n1 was changed to {x}\")\n\nsnells_law.n1.value = Medium.Air\n

Note

This signal will be emitted regardless of whether the parameter was changed in the GUI or via by directly setting the paramaeter on the gui instance.

"},{"location":"decorators/#usage-as-a-decorator-is-optional","title":"Usage As a Decorator is Optional","text":"

Remember: the @decorator syntax is just syntactic sugar. You don't have to use @magicgui to decorate your function declaration. You can also just call it with your function as an argument:

This decorator usage:

@magicgui(auto_call=True)\ndef function():\n    pass\n

is equivalent to this:

def function():\n    pass\n\nfunction = magicgui(function, auto_call=True)\n

In many cases, it will actually be desirable not to use magicgui as a decorator if you don't need a widget immediately, but want to create one later (see also the magic_factory decorator.)

# some time later...\nwidget_instance = magicgui(function)\n
"},{"location":"decorators/#magic_factory","title":"magic_factory","text":"

The magicgui.magic_factory function/decorator acts very much like the magicgui decorator, with one important difference:

Unlike magicgui, magic_factory does not return a widget instance immediately. Instead, it returns a \"factory function\" that can be called to create a widget instance.

This is an important distinction to understand. In most cases, the @magicgui decorator is useful for interactive use or rapid prototyping. But if you are writing a library or package where someone else will be instantiating your widget (a napari plugin is a good example), you will likely want to use magic_factory instead, (or create your own Widget Container subclass).

it's just a partial

If you're familiar with functools.partial, you can think of magic_factory as a partial function application of the magicgui decorator (in fact, magic_factory is a subclass of partial). It is very roughly equivalent to:

def magic_factory(func, *args, **kwargs):\n    return partial(magicgui, func, *args, **kwargs)\n
"},{"location":"decorators/#widget_init","title":"widget_init","text":"

magic_factory gains one additional parameter: widget_init. This accepts a callable that will be called with the new widget instance each time the factory is called. This is a convenient place to add additional initialization or connect events.

from magicgui import magic_factory\n\ndef _on_init(widget):\n    print(\"widget created!\", widget)\n    widget.y.changed.connect(lambda x: print(\"y changed!\", x))\n\n@magic_factory(widget_init=_on_init)\ndef my_factory(x: int, y: str): ...\n\nnew_widget = my_factory()\n
"},{"location":"decorators/#the-lack-of-magic-in-magicgui","title":"The (lack of) \"magic\" in magicgui","text":"

Just to demystify the name a bit, there really isn't a whole lot of \"magic\" in the magicgui decorator. It's really just a thin wrapper around the magicgui.widgets.create_widget function, to create a Container with a sub-widget for each parameter in the function signature.

The widget creation is very roughly equivalent to something like this:

from inspect import signature, Parameter\nfrom magicgui.widgets import create_widget, Container\nfrom magicgui.types import Undefined\n\n\ndef pseudo_magicgui(func: 'Callable'):\n    return Container(\n        widgets=[\n            create_widget(p.default, annotation=p.annotation, name=p.name)\n            for p in signature(func).parameters.values()\n        ]\n    )\n\ndef some_func(x: int = 2, y: str = 'hello'):\n    return x, y\n\nmy_widget = pseudo_magicgui(some_func)\nmy_widget.show()\n

In the case of magicgui, a special subclass of Container (FunctionGui) is used, which additionally adds a __call__ method that allows the widget to behave like the original function.

"},{"location":"events/","title":"Events","text":"

All magicgui widgets emit events when certain properties change. For each event there is a corresponding signal attribute on the widget that can be connected to a callback function. For example, a PushButton emits an event when it is clicked, and all ValueWidget subclasses (like Slider or LineEdit) emit an event when their value changes.

"},{"location":"events/#connecting-to-events","title":"Connecting to events","text":"

To connect a callback to an event, use the connect method of the signal attribute. The exact signals available on each widget are mostly defined in the base classes, and are listed on the API page for each respective widget.

For example, to connect a callback to a LineEdit widget's changed event:

Widget APImagicgui decoratormagic_factory decorator
from magicgui import widgets\n\ntext = widgets.LineEdit(value='type something')\ntext.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n
from magicgui import magicgui\n\n@magicgui\ndef my_function(text: str):\n    ...\n\nmy_function.text.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n
from magicgui import magic_factory\n\ndef _on_init(widget):\n    widget.text.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n\n@magic_factory(widget_init=_on_init)\ndef my_function(text: str):\n    ...\n\nmy_widget = my_function()\n

It's all psygnal under the hood

magicgui uses psygnal for its event system. For greater detail on the connect method and its options, see the Usage section of psygnal's documentation, or the psygnal.SignalInstance.connect API reference.

Tip

Note that connect returns the callable that it was passed, so you can use it as a decorator if you prefer.

text = widgets.LineEdit(value='type something')\n\n# this works\ntext.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n\n# so does this\n@text.changed.connect\ndef on_text_changed(val):\n    print(f\"Text changed to: {val}\")\n
"},{"location":"installation/","title":"Installation","text":"

magicgui is a pure Python package, and can be installed with pip:

pip install magicgui\n

or with conda:

conda install -c conda-forge magicgui\n
"},{"location":"installation/#backends","title":"Backends","text":"

magicgui requires a backend to be installed in order to function, but it does not specify a particular backend by default. The following backends are available:

Important

Note not all widgets are necessarily implemented for all backends. Most widgets in the widget docs specify which backends are supported.

"},{"location":"installation/#extras","title":"Extras","text":"

The Image widget requires pillow. You may use the image extra:

pip install magicgui[image]\n

The magicgui.tqdm module requires tqdm. You may use the tqdm extra:

pip install magicgui[tqdm]\n

The QuantityEdit widget requires pint. You may use the quantity extra:

pip install magicgui[quantity]\n
"},{"location":"type_map/","title":"Type Hints to Widgets","text":"

One of the key offerings of magicgui is the ability to automatically generate Widgets from Python type hints. This page describes how type hints are mapped to Widgets, and how to customize that mapping.

"},{"location":"type_map/#default-type-mapping","title":"Default Type Mapping","text":"

By default, The following python Type Hint annotations are mapped to the corresponding Widget class, and parametrized with the corresponding kwargs (when applicable):

Type Hint Widget __init__ kwargs bool Slider int Slider float FloatSlider str LineEdit range RangeEdit slice SliceEdit list ListEdit tuple TupleEdit pathlib.Path FileEdit os.PathLike FileEdit Sequence[pathlib.Path] FileEdit {'mode': 'rm'} datetime.time TimeEdit datetime.timedelta TimeEdit datetime.date DateEdit datetime.datetime DateTimeEdit Literal['a', 'b'] ComboBox {'choices': ['a', 'b']} Set[Literal['a', 'b']] Select {'choices': ('a', 'b')} enum.Enum ComboBox {'choices': <enum 'Enum'>} magicgui.widgets.ProgressBar ProgressBar {'bind': <function match_type.<locals>.<lambda> at 0x13b5ee3e0>, 'visible': True} types.FunctionType FunctionGui {'function': ...} pint.Quantity QuantityEdit"},{"location":"type_map/#example","title":"Example","text":"

from magicgui import widgets\nimport pathlib\nimport os\nimport datetime\nfrom typing import Literal, Set, Sequence\nimport types\nimport pint\nimport enum\n\ntypes = [\n    bool, int, float, str, range, slice, list,\n    pathlib.Path, os.PathLike, Sequence[pathlib.Path],\n    datetime.time, datetime.timedelta, datetime.date, datetime.datetime,\n    Literal['a', 'b'], Set[Literal['a', 'b']], enum.Enum,\n    widgets.ProgressBar, pint.Quantity,\n]\n\nwdg = widgets.Container(\n    widgets=[\n        widgets.create_widget(annotation=t, label=str(t)) for t in types\n    ]\n)\nwdg.show()\n

"},{"location":"type_map/#customizing-widget-options-with-typingannotated","title":"Customizing Widget Options with typing.Annotated","text":"

Widget options and types may be embedded in the type hint itself using typing.Annotated.

Note

This is not the only way to customize the widget type or options in magicgui. Some functions (like magicgui.magicgui) also accept **param_options keyword arguments that map parameter names to dictionaries of widget options.

"},{"location":"type_map/#overriding-the-default-type","title":"Overriding the Default Type","text":"

To override the widget class used for a given object type, use the widget_type key in the Annotated kwargs. It can be either the string name of one of the built-in widgets, or any Widget subclass object.

Type Hint Widget __init__ kwargs Annotated[int, {'widget_type': 'Slider'}] Slider Annotated[float, {'widget_type': 'FloatSlider'}] FloatSlider"},{"location":"type_map/#overriding-the-default-options","title":"Overriding the Default Options","text":"

Any additional kwargs will be passed to the widget constructor (and must be valid for the corresponding widget type).

Type Hint Widget __init__ kwargs Annotated[int, {'step': 10, 'max': 50}] Slider {'step': 10, 'max': 50} Annotated[int, {'choices': [1, 2, 3]}] Slider {'choices': [1, 2, 3]}"},{"location":"type_map/#examples","title":"Examples","text":"

Create a widget using standard type map:

create_widgetmagicgui decoratorguiclass decorator
my_widget = widgets.create_widget(value=42, annotation=int)\n
from magicgui import magicgui\n\n@magicgui\ndef my_widget(x: int = 42):\n    return x\n
from magicgui.experimental import guiclass\n\n@guiclass\nclass MyObject:\n    x: int = 42\n\nobj = MyObject()\nmy_widget = obj.gui\n

Customize a widget using typing.Annotated:

create_widgetmagicgui decoratorguiclass decorator
from typing import Annotated\n\nInt10_50 = Annotated[int, (('widget_type', 'Slider'),('step', 10),('max', 50))]\nwdg2 = widgets.create_widget(value=42, annotation=Int10_50)\n
from magicgui import magicgui\nfrom typing import Annotated\n\nInt10_50 = Annotated[int, (('widget_type', 'Slider'),('step', 10),('max', 50))]\n\n@magicgui\ndef my_widget(x: Int10_50 = 42):\n    ...\n
from magicgui.experimental import guiclass\nfrom typing import Annotated\n\nInt10_50 = Annotated[int, (('widget_type', 'Slider'),('step', 10),('max', 50))]\n\n@guiclass\nclass MyObject:\n    x: Int10_50 = 42\n\nobj = MyObject()\nmy_widget = obj.gui\n

Note that you may also customize widget creation with kwargs to create_widget

from typing import Annotated\nfrom magicgui.widgets import Slider\n\noptions = {'step': 10, 'max': 50}\nwdg3 = widgets.create_widget(value=42, widget_type=Slider, options=options)\nwdg3.show()\n

... or to the magicgui decorator:

@magicgui(x={'widget_type': 'Slider', 'step': 10, 'max': 50})\ndef my_widget(x: int = 42):\n    ...\n\nmy_widget.show()\n

"},{"location":"type_map/#return-type-mapping","title":"Return Type Mapping","text":"

In some cases, magicgui may be able to create a widget for the return annotation of a function.

... more to come ...

"},{"location":"type_map/#postponed-annotations","title":"Postponed annotations","text":"

Using forward references and __future__.annotations with magicgui is possible, but requires some extra care. Read on for more details.

"},{"location":"type_map/#forward-references","title":"Forward References","text":"

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later. This is called a Forward Reference (see PEP 484). This is useful when you want to use a type hint that refers to a type that has not yet been defined, or when you want to avoid importing a type that is only used in a type hint.

from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from mymodule import MyType\n\ndef my_function(x: 'MyType') -> None:\n    ...\n
"},{"location":"type_map/#__future__annotations","title":"__future__.annotations","text":"

In Python 3.7, the __future__.annotations feature was introduced (PEP 563), which postpones the evaluation of type annotations. The effect of this is that no type annotations will be evaluated at definition time, and all type annotations will be treated as strings (regardless of whether they are enclosed in quotes or not).

from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from mymodule import MyType\n\n# no longer necessary to use quotes around 'MyType'\ndef my_function(x: MyType) -> None:\n    ...\n

While this is a useful feature for developers, it does make it significantly more difficult to use those type annotations at runtime.

Magicgui does attempt to resolve forward references it encounters (see Resolving type hints at runtime for gory details), but this is an imperfect process, and may not always work.

"},{"location":"type_map/#if-you-must-use-postponed-annotations","title":"If You Must Use Postponed Annotations","text":"

As a general rule, if you must use forward references or __future__.annotations in a module that uses magicgui, you should:

"},{"location":"type_map/#registering-support-for-custom-types","title":"Registering Support for Custom Types","text":"

Any third-party library may use the magicgui.register_type function to register its types with magicgui. When a registered type is used as an annotation, the registered widget will be used.

"},{"location":"type_map/#known-third-party-support-for-magicgui","title":"Known Third-Party Support for magicgui","text":"

Hi developer!

Have a library that registers types with magicgui? Let us know and we'll add it to this list!

"},{"location":"type_map/#napari","title":"napari","text":"

napari has registered a number of its types to provide access to napari-specific objects using type annotations in magicgui. Details may be found in napari's documentation on using magicgui in napari.

"},{"location":"widgets/","title":"Widgets","text":"

Tip

If you're looking for an index of all available widgets, see the Widget Index.

All individual graphical elements in magicgui are \"widgets\", and all widgets are instances of magicgui.widgets.Widget. Widgets may be created directly:

from magicgui.widgets import LineEdit\n\nline_edit = LineEdit(value='hello!')\nline_edit.show()\n

Some widgets (such as magicgui.widgets.Container) are composite widgets that comprise other widgets:

from magicgui.widgets import LineEdit, SpinBox, Container\n\nline_edit = LineEdit(value='hello!')\nspin_box = SpinBox(value=400)\ncontainer = Container(widgets=[line_edit, spin_box])\ncontainer.show()\n

magicgui provides a way to automatically select a widget given a python value or type annotation using magicgui.widgets.create_widget. Here is an example that yields the same result as the one above:

from magicgui.widgets import create_widget\n\nx = 'hello!'\ny = 400\ncontainer = Container(widgets=[create_widget(i) for i in (x, y)])\ncontainer.show()\n

Tip

Because there are often multiple valid widget types for a given python object, you may sometimes wish to create widgets directly, or use the widget_type argument in create_widget()

"},{"location":"widgets/#the-widget-hierarchy","title":"The widget hierarchy","text":"
graph TB\n    A([Widget])-->B([ValueWidget])\n    A-->C([ContainerWidget])\n    B-->D([RangedWidget])\n    B-->E([ButtonWidget])\n    B-->F([CategoricalWidget])\n    C-->H([MainWindowWidget])\n    C-->G([FunctionGui])\n    D-->I([SliderWidget])\n    click A \"#widget\"\n    click B \"#valuewidget\"\n    click C \"#containerwidget\"\n    click D \"#rangedwidget\"\n    click E \"#buttonwidget\"\n    click F \"#categoricalwidget\"\n    click H \"#mainwindowwidget\"\n    click G \"#functiongui\"\n    click I \"#sliderwidget\"

Many widgets present similar types of information in different ways. magicgui tries to maintain a consistent API among all types of widgets that are designed to represent similar objects. The general class of widget you are working with will determine the properties and attributes it has.

Note

The categories shown below are sorted by their base class (such as ValueWidget and RangedWidget). The bases are not intended to be instantiated directly. Instead, you would create the widget type you wanted, such as LineEdit or SpinBox, respectively.

"},{"location":"widgets/#widget","title":"Widget","text":"

As mentioned above, all magicgui widgets derive from magicgui.widgets.Widget and have the following attributes (this list is not comprehensive, see the magicgui.widgets.Widget API):

Attribute Type Description name str The name or \"ID\" of this widget (such as a function parameter name to which this widget corresponds). annotation Any A type annotation for the value represented by the widget. label str A string to use for an associated Label widget (if this widget is being shown in a magicgui.widgets.Container widget, and container.labels is True). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI. tooltip str A tooltip to display when hovering over the widget. visible bool Whether the widget is visible."},{"location":"widgets/#valuewidget","title":"ValueWidget","text":"

In addition to the base Widget properties mentioned above, the following ValueWidgets track some value:

Widget Description Label A non-editable text display. LineEdit A one-line text editor. LiteralEvalLineEdit A one-line text editor that evaluates strings as python literals. Password A one-line text editor that obscures input. TextEdit A widget to edit and display both plain and rich text. FileEdit A LineEdit widget with a button that opens a FileDialog. RangeEdit A widget to represent a python range object, with start/stop/step. SliceEdit A widget to represent slice objects, with start/stop/step. DateTimeEdit A widget for editing dates and times. DateEdit A widget for editing dates. TimeEdit A widget for editing times. Table A widget to represent columnar or 2D data with headers. QuantityEdit A combined LineEdit and ComboBox to edit a pint.Quantity. Attribute Type Description value Any The current value of the widget. changed psygnal.SignalInstance A psygnal.SignalInstance that will emit an event when the value has changed. Connect callbacks to the change event using widget.changed.connect(callback) bind Any, optional A value or callback to bind this widget. If bound, whenever widget.value is accessed, the value provided here will be returned. The bound value can be a callable, in which case bound_value(self) will be returned (i.e. your callback must accept a single parameter, which is this widget instance.). see ValueWidget.bind for details.

Here is a demonstration of all these:

from magicgui import widgets\nimport datetime\n\nwdg_list = [\n    widgets.Label(value=\"label value\", label=\"Label:\"),\n    widgets.LineEdit(value=\"line edit value\", label=\"LineEdit:\"),\n    widgets.Password(value=\"super-secret!\", label=\"Password:\"),\n    widgets.TextEdit(value=\"text edit value...\", label=\"TextEdit:\"),\n    widgets.FileEdit(value=\"/home\", label=\"FileEdit:\"),\n    widgets.RangeEdit(value=range(0, 10, 2), label=\"RangeEdit:\"),\n    widgets.SliceEdit(value=slice(0, 10, 2), label=\"SliceEdit:\"),\n    widgets.DateTimeEdit(\n      value=datetime.datetime(1999, 12, 31, 11, 30), label=\"DateTimeEdit:\"\n    ),\n    widgets.DateEdit(value=datetime.date(81, 2, 18), label=\"DateEdit:\"),\n    widgets.TimeEdit(value=datetime.time(12, 20), label=\"TimeEdit:\"),\n    widgets.QuantityEdit(value='12 seconds', label=\"Quantity:\")\n]\ncontainer = widgets.Container(widgets=wdg_list)\ncontainer.max_height = 300\ncontainer.show()\n

"},{"location":"widgets/#rangedwidget","title":"RangedWidget","text":"

RangedWidgets are numerical ValueWidgets that have a restricted range of valid values, and a step size. RangedWidgets include:

Widget Description SpinBox A widget to edit an integer with clickable up/down arrows. FloatSpinBox A widget to edit a float with clickable up/down arrows.

In addition to all of the ValueWidget attributes, RangedWidget attributes include:

Attribute Type Description min float The minimum allowable value, by default 0 max float The maximum allowable value, by default 1000 step float The step size for incrementing the value, by default 1 range tuple of float A convenience attribute for getting/setting the (min, max) simultaneously

w1 = widgets.SpinBox(value=10, max=20, label='SpinBox:')\nw2 = widgets.FloatSpinBox(value=380, step=0.5, label='FloatSpinBox:')\ncontainer = widgets.Container(widgets=[w1, w2])\ncontainer.show()\n

"},{"location":"widgets/#sliderwidget","title":"SliderWidget","text":"

SliderWidgets are special RangedWidgets that additionally have an orientation, and a readout.

Widget Description Slider A slider widget to adjust an integer value within a range. FloatSlider A slider widget to adjust an integer value within a range. LogSlider A slider widget to adjust a numerical value logarithmically within a range. ProgressBar A progress bar widget.

In addition to all of the RangedWidget attributes, SliderWidget attributes include:

Attribute Type Description orientation str The orientation for the slider. Must be either 'horizontal' or 'vertical'. by default 'horizontal' readout bool Whether to show the value of the slider. By default, True.

w1 = widgets.Slider(value=10, max=25, label='Slider:')\nw2 = widgets.FloatSlider(value=10.5, max=18.5, label='FloatSlider:')\nw3 = widgets.ProgressBar(value=80, max=100, label='ProgressBar:')\ncontainer = widgets.Container(widgets=[w1, w2, w3])\ncontainer.show()\n

"},{"location":"widgets/#buttonwidget","title":"ButtonWidget","text":"

ButtonWidgets are boolean ValueWidgets that also have some text associated with them.

Widget Description PushButton A clickable command button. CheckBox A checkbox with a text label.

In addition to all of the ValueWidget attributes, ButtonWidget attributes include:

Attribute Type Description text str The text to display on the button. If not provided, will use name.

w1 = widgets.PushButton(value=True, text='PushButton Text')\nw2 = widgets.CheckBox(value=False, text='CheckBox Text')\ncontainer = widgets.Container(widgets=[w1, w2])\ncontainer.show()\n

"},{"location":"widgets/#categoricalwidget","title":"CategoricalWidget","text":"

CategoricalWidget are ValueWidgets that provide a set of valid choices. They can be created from:

Widget Description ComboBox A dropdown menu, allowing selection between multiple choices. RadioButtons An exclusive group of radio buttons, providing a choice from multiple choices. Select A list of options, allowing selection between multiple choices.

In addition to all of the ValueWidget attributes, CategoricalWidget attributes include:

Attribute Type Description choices Enum, Iterable, or Callable Available choices displayed in the widget. value Any In the case of a CategoricalWidget the value is the data of the currently selected choice (see also: current_choice below). current_choice str The name associated with the current choice. For instance, if choices was provided as choices=[('one', 1), ('two', 2)], then an example value would be 1, and an example current_choice would be 'one'.

choices = ['one', 'two', 'three']\nw1 = widgets.ComboBox(choices=choices, value='two', label='ComboBox:')\nw2 = widgets.RadioButtons(choices=choices, label='RadioButtons:')\nw3 = widgets.Select(choices=choices, label='Select:')\ncontainer = widgets.Container(widgets=[w1, w2, w3])\ncontainer.max_height = 220\ncontainer.show()\n

"},{"location":"widgets/#containerwidget","title":"ContainerWidget","text":"

A ContainerWidget is a list-like Widget that can contain other widgets. Containers allow you to build more complex widgets from sub-widgets. A notable example of a Container is magicgui.widgets.FunctionGui) (the product of the @magicgui decorator).

Widget Description Container A Widget to contain other widgets. MainWindow A Widget to contain other widgets, includes a menu bar. FunctionGui Wrapper for a container of widgets representing a callable object. Attribute Type Description layout str The layout for the container. Must be either 'horizontal' or 'vertical'. widgets Sequence[Widget] The widgets that the container contains. labels bool Whether each widget should be shown with a corresponding Label widget to the left. Note: the text for each widget defaults to widget.name, but can be overridden by setting widget.label.

Container implements the full collections.abc.MutableSequence interface. You can add and remove widgets from it just as you would add or remove items from a list.

from magicgui.widgets import Container, Slider, FloatSlider, ProgressBar\n\ncontainer = widgets.Container()\ncontainer.append(widgets.LineEdit(value='Mookie', label='Your Name:'))\ncontainer.append(widgets.FloatSlider(value=10.5, label='FloatSlider:'))\ncontainer.show()\n

"},{"location":"widgets/#mainwindowwidget","title":"MainWindowWidget","text":"

A MainWindowWidget is a special type of ContainerWidget that also includes a menu bar.

"},{"location":"widgets/#functiongui","title":"FunctionGui","text":"

A FunctionGui is a special type of ContainerWidget that is created from a function. It is the product of the @magicgui decorator. It is a container that contains a widget for each of the parameters in the function. See magicgui.widgets.FunctionGui for details.

"},{"location":"widgets/#magicgui","title":"@magicgui","text":"

It's worth noting that @magicgui and @magic_factory decorators are just conveniences that build a special type of Container widget (a FunctionGui), with a widget representing each of the parameters in a decorated function.

from magicgui import magicgui\n\n@magicgui\ndef my_function(x='hello', y=400): ...\n\nmy_function.show()\n

In terms of simply building widgets, the following code performs a similar task to @magicgui.

from inspect import signature\n\ndef my_function(x='hello', y=400):\n  ...\n\nparams = signature(my_function).parameters.values()\ncontainer = Container(\n    widgets=[create_widget(p.default, name=p.name) for p in params]\n)\ncontainer.show()\n

Tip

Note that the FunctionGui widget produced by @magicgui is actually a callable object that behaves very much like the original function, except that it will use current values from the GUI as default parameters when calling the function.

"},{"location":"api/app/","title":"Application","text":""},{"location":"api/app/#magicgui.application.Application","title":"magicgui.application.Application","text":"

Magicgui Application, wrapping a native BaseApplicationBackend implementation.

"},{"location":"api/app/#magicgui.application.Application.backend_module","title":"backend_module: ModuleType property","text":"

Return module object that defines the backend.

"},{"location":"api/app/#magicgui.application.Application.backend_name","title":"backend_name: str property","text":"

Return name of the GUI backend that this app wraps.

"},{"location":"api/app/#magicgui.application.Application.native","title":"native: Any property","text":"

Return the native GUI application instance.

"},{"location":"api/app/#magicgui.application.Application.__enter__","title":"__enter__() -> Application","text":"

Context manager to start this application.

"},{"location":"api/app/#magicgui.application.Application.__exit__","title":"__exit__(*exc_details: Any) -> None","text":"

Exit context manager for this application.

"},{"location":"api/app/#magicgui.application.Application.__repr__","title":"__repr__() -> str","text":"

Return repr for this instance.

"},{"location":"api/app/#magicgui.application.Application.create","title":"create() -> None","text":"

Create the native application.

"},{"location":"api/app/#magicgui.application.Application.get_obj","title":"get_obj(name: str) -> Any","text":"

Get the backend object for the given name (such as a widget).

"},{"location":"api/app/#magicgui.application.Application.process_events","title":"process_events() -> None","text":"

Process all pending GUI events.

"},{"location":"api/app/#magicgui.application.Application.quit","title":"quit() -> None","text":"

Quit the native GUI event loop.

"},{"location":"api/app/#magicgui.application.Application.run","title":"run() -> None","text":"

Enter the native GUI event loop.

"},{"location":"api/app/#magicgui.application.Application.start_timer","title":"start_timer(interval: int = 1000, on_timeout: Callable[[], None] | None = None, single_shot: bool = False) -> None","text":"

Start a timer with a given interval, optional callback, and single_shot.

"},{"location":"api/app/#magicgui.application.use_app","title":"magicgui.application.use_app(app: AppRef | None = None) -> Application","text":"

Get/create the default Application object. See _use_app docstring.

"},{"location":"api/experimental/","title":"magicgui.experimental","text":"

Experimental

This module contains experimental features that are not yet ready for prime time. All of the features in this module are subject to change without warning or deprecation.

"},{"location":"api/experimental/#magicgui.experimental.guiclass","title":"magicgui.experimental.guiclass(cls: T | None = None, *, gui_name: str = 'gui', events_namespace: str = 'events', follow_changes: bool = True, **dataclass_kwargs: Any) -> T | Callable[[T], T]","text":"

Turn class into a dataclass with a property (gui_name) that returns a gui.

This decorator is similar to dataclasses.dataclass, but it will also add an events attribute to the class that is an instance of psygnal.SignalGroup (with a signal for each field in the dataclass; see https://psygnal.readthedocs.io/en/latest/dataclasses/ for details), and a gui property that returns a magicgui widget, bound to the values of the dataclass instance.

Note

This decorator is compatible with dataclasses using slots=True, however, there is a potential for a memory leak that the user should be aware of. If you create a guiclass instance, and then store a reference to its gui, and then delete the instance, the gui will still be bound to the instance, preventing it from being garbage collected. To avoid this, you can call unbind_gui_from_instance(gui, instance) before deleting the instance.

Parameters:

Returns:

Examples:

>>> @guiclass\n... class MyData:\n...     x: int = 0\n...     y: str = 'hi'\n...\n...     @button\n...     def reset(self):\n...         self.x = 0\n...         self.y = 'hi'\n...\n>>> data = MyData()\n>>> data.gui.show()\n
"},{"location":"api/experimental/#magicgui.experimental.button","title":"magicgui.experimental.button(func: F | None = None, **button_kwargs: Any) -> F | Callable[[F], F]","text":"

Add a method as a button to a guiclass, which calls the decorated method.

Parameters:

"},{"location":"api/experimental/#magicgui.experimental.is_guiclass","title":"magicgui.experimental.is_guiclass(obj: object) -> TypeGuard[GuiClassProtocol]","text":"

Return True if obj is a guiclass or an instance of a guiclass.

"},{"location":"api/magic_factory/","title":"magicgui.magic_factory","text":""},{"location":"api/magic_factory/#magicgui.magic_factory","title":"magicgui.magic_factory(function=None, *, layout='vertical', scrollable=False, labels=True, tooltips=True, call_button=None, auto_call=False, result_widget=False, main_window=False, app=None, persist=False, widget_init=None, raise_on_unknown=False, **param_options)","text":"

Return a MagicFactory for function.

magic_factory is nearly identical to the magicgui decorator with the following differences:

  1. Whereas magicgui returns a FunctionGui instance, magic_factory returns a callable that returns a FunctionGui instance. (Technically, it returns an instance of MagicFactory which you behaves exactly like a functools.partial for a FunctionGui instance.)
  2. magic_factory adds a widget_init method: a callable that will be called immediately after the FunctionGui instance is created. This can be used to add additional widgets to the layout, or to connect signals to the widgets.

Important

Whereas decorating a function with magicgui will immediately create a widget instance, magic_factory will not create a widget instance until the decorated object is called. This is often what you want in a library, whereas magicgui is useful for rapid, interactive development.

Parameters:

Returns:

Examples:

>>> @magic_factory\n... def my_function(a: int = 1, b: str = 'hello'):\n...     pass\n...\n>>> my_widget = my_function()\n>>> my_widget.show()\n>>> my_widget.a.value == 1  # True\n>>> my_widget.b.value = 'world'\n
"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory","title":"magicgui.type_map._magicgui.MagicFactory","text":"

Bases: partial, Generic[_FGuiVar]

Factory function that returns a FunctionGui instance.

While this can be used directly, (see example below) the preferred usage is via the magicgui.magic_factory decorator.

Examples:

>>> def func(x: int, y: str):\n...     pass\n...\n>>> factory = MagicFactory(function=func, labels=False)\n>>> # factory accepts all the same arguments as magicgui()\n>>> widget1 = factory(call_button=True)\n>>> # can also override magic_kwargs that were provided when creating the factory\n>>> widget2 = factory(auto_call=True, labels=True)\n
"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__name__","title":"__name__: str property","text":"

Pass function name.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__call__","title":"__call__(*args, **kwargs)","text":"

Call the wrapped _magicgui and return a FunctionGui.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__getattr__","title":"__getattr__(name)","text":"

Allow accessing FunctionGui attributes without mypy error.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__new__","title":"__new__(function, *args, magic_class=FunctionGui, widget_init=None, **keywords)","text":"

Create new MagicFactory.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__repr__","title":"__repr__()","text":"

Return string repr.

"},{"location":"api/magicgui/","title":"magicgui.magicgui","text":""},{"location":"api/magicgui/#magicgui.magicgui","title":"magicgui.magicgui(function=None, *, layout='vertical', scrollable=False, labels=True, tooltips=True, call_button=None, auto_call=False, result_widget=False, main_window=False, app=None, persist=False, raise_on_unknown=False, **param_options)","text":"

Return a FunctionGui for function.

Parameters:

Returns:

Examples:

>>> @magicgui\n... def my_function(a: int = 1, b: str = 'hello'):\n...     pass\n...\n>>> my_function.show()\n>>> my_function.a.value == 1  # True\n>>> my_function.b.value = 'world'\n
"},{"location":"api/migration/","title":"migration guide","text":""},{"location":"api/migration/#v030-migration-guide","title":"v0.3.0 migration guide","text":"

October, 2021

Version 0.3.0 of magicgui introduced some changes to the events and callbacks API. See https://github.com/pyapp-kit/magicgui/pull/253 for details

"},{"location":"api/migration/#callbacks-now-receive-the-value-directly-instead-of-an-event-object","title":"Callbacks now receive the value directly, instead of an Event object","text":"

magicgui 0.3.0 is now using psygnal as its event/callback handler.

Callbacks connected to widget.changed (and other event emitters) may now receive the value(s) directly, instead of an event object:

\ud83d\udc4e Old Method (< v0.3.0)
@widget.changed.connect\ndef my_callback(event):\n    # event was an `Event` object with a `value` attribute\n    new_value = event.value\n

Existing code using callbacks with a single positional argument will continue to receive a single Event object (and a warning will be shown, until v0.4.0 where it will become an error).

To silence the warning and opt in to the new pattern of receiving value directly, you can do one of two things:

  1. type hint your single positional argument as anything other than magicgui.events.Event
  2. provide a callback that takes no arguments
\ud83d\udc4d New Method (>= v0.3.0)
@widget.changed.connect\ndef my_callback(new_value: int):\n    ...  # use new_value directly\n\n# or, if you don't need to use new_value\n@widget.changed.connect\ndef my_callback():\n    # something that didn't need the value\n    ...\n
"},{"location":"api/migration/#event-emitters-take-no-keyword-arguments","title":"Event emitters take no keyword arguments","text":"

For the few packages who were manually emitting change events, you should no longer provide the value= keyword when emitting.

\ud83d\udc4e Old Method (< v0.3.0)
widget.changed(value='whatever')\n
\ud83d\udc4d New Method (>= v0.3.0)
widget.changed.emit('whatever')\n# OR (if you prefer the direct __call__ syntax)\nwidget.changed('whatever')\n
"},{"location":"api/migration/#v020-migration-guide","title":"v0.2.0 migration guide","text":"

December, 2020

Version 0.2.0 of magicgui was a complete rewrite that introduced a couple breaking API changes

"},{"location":"api/migration/#gui-attribute-removed","title":".Gui() attribute removed","text":"

Before v0.2.0, the magicgui.magicgui decorator added a Gui attribute to the decorated function that was to be called to instantiate a widget. In v0.2.0 the object returned from the magicgui.magicgui decorator is already an instantiated magicgui.widgets.Widget.

\ud83d\udc4e Old Method (< v0.2.0)
from magicgui import magicgui, event_loop\n\n@magicgui\ndef function(x, y):\n    ...\n\nwith event_loop():\n    gui = function.Gui(show=True)\n
\ud83d\udc4d New Method (>= v0.2.0)
from magicgui import magicgui\n\n@magicgui\ndef function(x, y):\n    ...\n\nfunction.show(run=True)\n
"},{"location":"api/migration/#new-base-widget-type","title":"New base widget type","text":"

Before v0.2.0, the Gui() object returned by the magicgui.magicgui decorator was a MagicGuiBase widget class, which in turn was a direct subclass of a backend widget, such as a QtWidgets.QWidget. In v0.2.0, all widgets derive from [magicgui.widgets.Widget``][magicgui.widgets.Widget], and the *backend* is available atwidget.native. If you are incorporating magicgui widgets into a larger Qt-based GUI, please note that you will want to usewidget.nativeinstead ofwidget`

from magicgui import magicgui, use_app\n\nuse_app('qt')\n\n@magicgui\ndef function(x, y):\n    ...\n
>>> print(type(function))\n<class 'magicgui.widgets.FunctionGui'>\n>>> print(type(function.native))\n<class 'PyQt5.QtWidgets.QWidget'>\n
"},{"location":"api/migration/#starting-the-application","title":"Starting the application","text":"

It is now easier to show a widget and start an application by calling widget.show(run=True). Calling show(run=True) will immediately block execution of your script and show the widget. If you wanted to (for instance) show multiple widgets next to each other, then you would still want to use the event_loop context manager:

from magicgui import magicgui, event_loop\n\n@magicgui\ndef function_a(x=1, y=3):\n    ...\n\n@magicgui\ndef function_b(z='asdf'):\n    ...\n\nwith event_loop():\n    function_a.show()\n    function_b.show()\n# both widgets will show (though b may be on top of a)\n
"},{"location":"api/migration/#getting-and-setting-values","title":"Getting and setting values","text":"

To get or set the value of a widget programmatically, you no longer set the corresponding widget attribute directly, but rather use the widget.value attribute:

Old Method \ud83d\udc4e

gui.x used to be a descriptor object to get/set the value, but the actual underlying widget was at gui.x_widget

gui = function.Gui()\ngui.x = 10\n

New Method \ud83d\udc4d

now function.x IS the widget, and you set its value with function.x.value

function.x.value = 10\n
"},{"location":"api/migration/#connecting-callbacks-to-events","title":"Connecting callbacks to events","text":"

When binding callbacks to change events, you no longer connect to gui.<name>_changed, you now connect to function.<name>.changed:

\ud83d\udc4e Old Method (< v0.2.0)
gui = function.Gui()\ngui.x_changed.connect(my_callback)\n
\ud83d\udc4d New Method (>= v0.2.0)
function.x.changed.connect(my_callback)\n
"},{"location":"api/migration/#renamed","title":"Renamed","text":""},{"location":"api/protocols/","title":"Backend Protocols","text":"

Advanced Topic

Most users of magicgui will not need to worry about this section.

These Protocol classes declare the interface that backend adapters must implement in order to be used by magicgui. All magicgui Widget objects compose a backend widget implementing one of these protocols, and control it using the methods defined herein.

magicgui developers may be interested in this page, but end-users needn't worry about it.

"},{"location":"api/protocols/#summary","title":"Summary","text":"Widget Description WidgetProtocol Base Widget Protocol: specifies methods that all widgets must provide. ValueWidgetProtocol Widget that has a current value, with getter/setter and on_change callback. ButtonWidgetProtocol The \"value\" in a ButtonWidget is the current (checked) state. TableWidgetProtocol ValueWidget subclass intended for 2D tabular data, with row & column headers. RangedWidgetProtocol Value widget that supports numbers within a provided min/max range. CategoricalWidgetProtocol Categorical widget, that has a set of valid choices, and a current value. SliderWidgetProtocol Protocol for implementing a slider widget. ContainerProtocol Widget that can contain other widgets. BaseApplicationBackend Backend Application object. DialogProtocol Protocol for modal (blocking) containers. SupportsChoices Widget that has a set of valid choices. SupportsOrientation Widget that can be reoriented. SupportsText Widget that have text (in addition to value)... like buttons. SupportsReadOnly Widget that can be read_only."},{"location":"api/protocols/#protocol-inheritance","title":"Protocol Inheritance","text":"

The visual hierarchy of protocols looks like this:

graph LR\n    A([WidgetProtocol])-->B([ValueWidgetProtocol])\n    A-->C([ContainerProtocol])\n    M([SupportsText])-->E\n    B-->E([ButtonWidgetProtocol])\n    B-->D([RangedWidgetProtocol])\n    B-->F([CategoricalWidgetProtocol])\n    D-->I([SliderWidgetProtocol])\n    B-->J([TableWidgetProtocol])\n    K([SupportsReadOnly])-->J([TableWidgetProtocol])\n    L([SupportsChoices])-->F\n    N([SupportsOrientation])-->C\n    N-->I\n    C-->O([DialogProtocol])\n    C-->P([MainWindowProtocol])\n\n    click A \"#magicgui.widgets.protocols.WidgetProtocol\"\n    click B \"#magicgui.widgets.protocols.ValueWidgetProtocol\"\n    click C \"#magicgui.widgets.protocols.ContainerProtocol\"\n    click D \"#magicgui.widgets.protocols.RangedWidgetProtocol\"\n    click E \"#magicgui.widgets.protocols.ButtonWidgetProtocol\"\n    click F \"#magicgui.widgets.protocols.CategoricalWidgetProtocol\"\n    click I \"#magicgui.widgets.protocols.SliderWidgetProtocol\"\n    click J \"#magicgui.widgets.protocols.TableWidgetProtocol\"\n    click K \"#magicgui.widgets.protocols.SupportsReadOnly\"\n    click L \"#magicgui.widgets.protocols.SupportsChoices\"\n    click M \"#magicgui.widgets.protocols.SupportsText\"\n    click N \"#magicgui.widgets.protocols.SupportsOrientation\"\n    click O \"#magicgui.widgets.protocols.DialogProtocol\"\n    click P \"#magicgui.widgets.protocols.MainWindowProtocol\"
"},{"location":"api/protocols/#widget-protocols","title":"Widget Protocols","text":""},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol","title":"magicgui.widgets.protocols.WidgetProtocol","text":"

Bases: Protocol

Base Widget Protocol: specifies methods that all widgets must provide.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_bind_parent_change_callback","title":"_mgui_bind_parent_change_callback(callback: Callable[[Any], None]) -> None abstractmethod","text":"

Bind callback to parent change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_close_widget","title":"_mgui_close_widget() -> None abstractmethod","text":"

Close widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_enabled","title":"_mgui_get_enabled() -> bool abstractmethod","text":"

Get the enabled state of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_height","title":"_mgui_get_height() -> int abstractmethod","text":"

Get the height of the widget.

The intention is to get the height of the widget after it is shown, for the purpose of unifying widget height in a layout. Backends may do what they need to accomplish this. For example, Qt can use sizeHint().height(), since height() may return something large if the widget has not yet been painted on screen.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_max_height","title":"_mgui_get_max_height() -> int abstractmethod","text":"

Get the maximum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_max_width","title":"_mgui_get_max_width() -> int abstractmethod","text":"

Get the maximum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_min_height","title":"_mgui_get_min_height() -> int abstractmethod","text":"

Get the minimum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_min_width","title":"_mgui_get_min_width() -> int abstractmethod","text":"

Get the minimum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_native_widget","title":"_mgui_get_native_widget() -> Any abstractmethod","text":"

Return the native backend widget instance.

This is generally the widget that has the layout.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_parent","title":"_mgui_get_parent() -> Widget abstractmethod","text":"

Return the parent widget of this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_root_native_widget","title":"_mgui_get_root_native_widget() -> Any abstractmethod","text":"

Return the root native backend widget.

In most cases, this is the same as _mgui_get_native_widget. However, in cases where the native widget is in a scroll layout, this might be different.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_tooltip","title":"_mgui_get_tooltip() -> str abstractmethod","text":"

Get the tooltip for this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_visible","title":"_mgui_get_visible() -> bool abstractmethod","text":"

Get widget visibility.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_width","title":"_mgui_get_width() -> int abstractmethod","text":"

Get the width of the widget.

The intention is to get the width of the widget after it is shown, for the purpose of unifying widget width in a layout. Backends may do what they need to accomplish this. For example, Qt can use sizeHint().width(), since width() may return something large if the widget has not yet been painted on screen.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_render","title":"_mgui_render() -> np.ndarray abstractmethod","text":"

Return an RGBA (MxNx4) numpy array bitmap of the rendered widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_enabled","title":"_mgui_set_enabled(enabled: bool) -> None abstractmethod","text":"

Set the enabled state of the widget to enabled.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_height","title":"_mgui_set_height(value: int) -> None abstractmethod","text":"

Set the height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_max_height","title":"_mgui_set_max_height(value: int) -> None abstractmethod","text":"

Set the maximum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_max_width","title":"_mgui_set_max_width(value: int) -> None abstractmethod","text":"

Set the maximum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_min_height","title":"_mgui_set_min_height(value: int) -> None abstractmethod","text":"

Set the minimum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_min_width","title":"_mgui_set_min_width(value: int) -> None abstractmethod","text":"

Set the minimum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_parent","title":"_mgui_set_parent(widget: Widget) -> None abstractmethod","text":"

Set the parent widget of this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_tooltip","title":"_mgui_set_tooltip(value: str | None) -> None abstractmethod","text":"

Set a tooltip for this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_visible","title":"_mgui_set_visible(value: bool) -> None abstractmethod","text":"

Set widget visibility.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_width","title":"_mgui_set_width(value: int) -> None abstractmethod","text":"

Set the width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol","title":"magicgui.widgets.protocols.ValueWidgetProtocol","text":"

Bases: WidgetProtocol, Protocol

Widget that has a current value, with getter/setter and on_change callback.

It is worth noting that the widget is the thing that has a value. Magicgui does not maintain & synchronize an independent model.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol._mgui_bind_change_callback","title":"_mgui_bind_change_callback(callback: Callable[[Any], Any]) -> None abstractmethod","text":"

Bind callback to value change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol._mgui_get_value","title":"_mgui_get_value() -> Any abstractmethod","text":"

Get current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol._mgui_set_value","title":"_mgui_set_value(value: Any) -> None abstractmethod","text":"

Set current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ButtonWidgetProtocol","title":"magicgui.widgets.protocols.ButtonWidgetProtocol","text":"

Bases: ValueWidgetProtocol, SupportsText, Protocol

The \"value\" in a ButtonWidget is the current (checked) state.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol","title":"magicgui.widgets.protocols.TableWidgetProtocol","text":"

Bases: ValueWidgetProtocol, SupportsReadOnly, Protocol

ValueWidget subclass intended for 2D tabular data, with row & column headers.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_bind_change_callback","title":"_mgui_bind_change_callback(callback: Callable[[Any], Any]) -> None abstractmethod","text":"

Bind callback to value change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_bind_column_headers_change_callback","title":"_mgui_bind_column_headers_change_callback(callback: Callable[[Any], None]) -> None abstractmethod","text":"

Bind callback to column headers change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_bind_row_headers_change_callback","title":"_mgui_bind_row_headers_change_callback(callback: Callable[[Any], None]) -> None abstractmethod","text":"

Bind callback to row headers change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_cell","title":"_mgui_get_cell(row: int, col: int) -> Any abstractmethod","text":"

Get current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_column_count","title":"_mgui_get_column_count() -> int abstractmethod","text":"

Get the number of columns in the table.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_column_headers","title":"_mgui_get_column_headers() -> tuple abstractmethod","text":"

Get current column headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_row_count","title":"_mgui_get_row_count() -> int abstractmethod","text":"

Get the number of rows in the table.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_row_headers","title":"_mgui_get_row_headers() -> tuple abstractmethod","text":"

Get current row headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_remove_column","title":"_mgui_remove_column(column: int) -> None abstractmethod","text":"

Remove column at index column.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_remove_row","title":"_mgui_remove_row(row: int) -> None abstractmethod","text":"

Remove row at index row.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_cell","title":"_mgui_set_cell(row: int, col: int, value: Any) -> None abstractmethod","text":"

Set current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_column_count","title":"_mgui_set_column_count(ncols: int) -> None abstractmethod","text":"

Set the number of columns in the table. (Create/delete as needed).

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_column_headers","title":"_mgui_set_column_headers(headers: Sequence) -> None abstractmethod","text":"

Set current column headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_row_count","title":"_mgui_set_row_count(nrows: int) -> None abstractmethod","text":"

Set the number of rows in the table. (Create/delete as needed).

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_row_headers","title":"_mgui_set_row_headers(headers: Sequence) -> None abstractmethod","text":"

Set current row headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol","title":"magicgui.widgets.protocols.RangedWidgetProtocol","text":"

Bases: ValueWidgetProtocol, Protocol

Value widget that supports numbers within a provided min/max range.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_adaptive_step","title":"_mgui_get_adaptive_step() -> bool abstractmethod","text":"

Get adaptive step status.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_max","title":"_mgui_get_max() -> float abstractmethod","text":"

Get the maximum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_min","title":"_mgui_get_min() -> float abstractmethod","text":"

Get the minimum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_step","title":"_mgui_get_step() -> float abstractmethod","text":"

Get the step size.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_adaptive_step","title":"_mgui_set_adaptive_step(value: bool) -> None abstractmethod","text":"

Set adaptive step status.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_max","title":"_mgui_set_max(value: float) -> None abstractmethod","text":"

Set the maximum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_min","title":"_mgui_set_min(value: float) -> None abstractmethod","text":"

Set the minimum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_step","title":"_mgui_set_step(value: float) -> None abstractmethod","text":"

Set the step size.

"},{"location":"api/protocols/#magicgui.widgets.protocols.CategoricalWidgetProtocol","title":"magicgui.widgets.protocols.CategoricalWidgetProtocol","text":"

Bases: ValueWidgetProtocol, SupportsChoices, Protocol

Categorical widget, that has a set of valid choices, and a current value.

It adds no additional methods.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol","title":"magicgui.widgets.protocols.SliderWidgetProtocol","text":"

Bases: RangedWidgetProtocol, SupportsOrientation, Protocol

Protocol for implementing a slider widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol._mgui_get_tracking","title":"_mgui_get_tracking() -> bool","text":"

If tracking is False, changed is only emitted when released.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol._mgui_set_readout_visibility","title":"_mgui_set_readout_visibility(visible: bool) -> None","text":"

Set visibility of readout widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol._mgui_set_tracking","title":"_mgui_set_tracking(tracking: bool) -> None","text":"

If tracking is False, changed is only emitted when released.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol","title":"magicgui.widgets.protocols.ContainerProtocol","text":"

Bases: WidgetProtocol, SupportsOrientation, Protocol

Widget that can contain other widgets.

This generally manages a backend Layout.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_get_margins","title":"_mgui_get_margins() -> tuple[int, int, int, int] abstractmethod","text":"

Get the margins of the container.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_insert_widget","title":"_mgui_insert_widget(position: int, widget: Widget) -> None abstractmethod","text":"

Insert widget at the given position in the layout.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_remove_widget","title":"_mgui_remove_widget(widget: Widget) -> None abstractmethod","text":"

Remove the specified widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_set_margins","title":"_mgui_set_margins(margins: tuple[int, int, int, int]) -> None abstractmethod","text":"

Set the margins of the container.

"},{"location":"api/protocols/#magicgui.widgets.protocols.DialogProtocol","title":"magicgui.widgets.protocols.DialogProtocol","text":"

Bases: ContainerProtocol, Protocol

Protocol for modal (blocking) containers.

"},{"location":"api/protocols/#magicgui.widgets.protocols.DialogProtocol._mgui_exec","title":"_mgui_exec() -> None abstractmethod","text":"

Show the dialog and block.

"},{"location":"api/protocols/#magicgui.widgets.protocols.MainWindowProtocol","title":"magicgui.widgets.protocols.MainWindowProtocol","text":"

Bases: ContainerProtocol, Protocol

Application main widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.MainWindowProtocol._mgui_create_menu_item","title":"_mgui_create_menu_item(menu_name: str, action_name: str, callback: Callable | None = None, shortcut: str | None = None) -> None abstractmethod","text":"

Create a new menu item.

Parameters:

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices","title":"magicgui.widgets.protocols.SupportsChoices","text":"

Bases: Protocol

Widget that has a set of valid choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_del_choice","title":"_mgui_del_choice(choice_name: str) -> None abstractmethod","text":"

Delete the provided choice_name and associated data.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_choice","title":"_mgui_get_choice(choice_name: str) -> Any abstractmethod","text":"

Get data for a single choice.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_choices","title":"_mgui_get_choices() -> tuple[tuple[str, Any], ...] abstractmethod","text":"

Get available choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_count","title":"_mgui_get_count() -> int abstractmethod","text":"

Return number of choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_current_choice","title":"_mgui_get_current_choice() -> str abstractmethod","text":"

Return the text of the currently selected choice.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_set_choice","title":"_mgui_set_choice(choice_name: str, data: Any) -> None abstractmethod","text":"

Set data for choice_name, or add a new item if choice_name doesn't exist.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_set_choices","title":"_mgui_set_choices(choices: Iterable[tuple[str, Any]]) -> None abstractmethod","text":"

Set available choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsOrientation","title":"magicgui.widgets.protocols.SupportsOrientation","text":"

Bases: Protocol

Widget that can be reoriented.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsOrientation._mgui_get_orientation","title":"_mgui_get_orientation() -> str abstractmethod","text":"

Get orientation, return either 'horizontal' or 'vertical'.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsOrientation._mgui_set_orientation","title":"_mgui_set_orientation(value: str) -> None abstractmethod","text":"

Set orientation, value will be 'horizontal' or 'vertical'.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsText","title":"magicgui.widgets.protocols.SupportsText","text":"

Bases: Protocol

Widget that have text (in addition to value)... like buttons.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsText._mgui_get_text","title":"_mgui_get_text() -> str abstractmethod","text":"

Get text.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsText._mgui_set_text","title":"_mgui_set_text(value: str) -> None abstractmethod","text":"

Set text.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsReadOnly","title":"magicgui.widgets.protocols.SupportsReadOnly","text":"

Bases: Protocol

Widget that can be read_only.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsReadOnly._mgui_get_read_only","title":"_mgui_get_read_only() -> bool abstractmethod","text":"

Get read_only status.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsReadOnly._mgui_set_read_only","title":"_mgui_set_read_only(value: bool) -> None abstractmethod","text":"

Set read_only.

"},{"location":"api/protocols/#application-protocol","title":"Application Protocol","text":""},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend","title":"magicgui.widgets.protocols.BaseApplicationBackend","text":"

Bases: ABC

Backend Application object.

Abstract class that provides an interface between backends and Application. Each backend must implement a subclass of BaseApplicationBackend, and implement all of its _mgui_xxx methods.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_get_backend_name","title":"_mgui_get_backend_name() -> str abstractmethod","text":"

Return the name of the backend.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_get_native_app","title":"_mgui_get_native_app() -> Any abstractmethod","text":"

Return the native GUI application instance.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_process_events","title":"_mgui_process_events() -> None abstractmethod","text":"

Process all pending GUI events.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_quit","title":"_mgui_quit() -> None abstractmethod","text":"

Quit the native GUI event loop.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_run","title":"_mgui_run() -> None abstractmethod","text":"

Start the application.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_start_timer","title":"_mgui_start_timer(interval: int = 0, on_timeout: Callable[[], None] | None = None, single: bool = False) -> None abstractmethod","text":"

Create and start a timer.

Parameters:

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_stop_timer","title":"_mgui_stop_timer() -> None abstractmethod","text":"

Stop timer. Should check for the existence of the timer.

"},{"location":"api/type_map/","title":"magicgui.type_map","text":"Widget Description get_widget_class Return a Widget subclass for the value/annotation. register_type Register a widget_type to be used for all parameters with type type_. type_registered Context manager that temporarily registers a widget type for a given type_. type2callback Return any callbacks that have been registered for type_."},{"location":"api/type_map/#magicgui.type_map.get_widget_class","title":"magicgui.type_map.get_widget_class(value: Any = Undefined, annotation: Any = Undefined, options: dict | None = None, is_result: bool = False, raise_on_unknown: bool = True) -> tuple[WidgetClass, dict]","text":"

Return a Widget subclass for the value/annotation.

Parameters:

Returns:

"},{"location":"api/type_map/#magicgui.type_map.register_type","title":"magicgui.type_map.register_type(type_: _T | None = None, *, widget_type: WidgetRef | None = None, return_callback: ReturnCallback | None = None, **options: Any) -> _T | Callable[[_T], _T]","text":"

Register a widget_type to be used for all parameters with type type_.

Note: registering a Union (or Optional) type effectively registers all types in the union with the arguments.

Parameters:

Raises:

"},{"location":"api/type_map/#magicgui.type_map.type_registered","title":"magicgui.type_map.type_registered(type_: _T, *, widget_type: WidgetRef | None = None, return_callback: ReturnCallback | None = None, **options: Any) -> Iterator[None]","text":"

Context manager that temporarily registers a widget type for a given type_.

When the context is exited, the previous widget type associations for type_ is restored.

Parameters:

"},{"location":"api/type_map/#magicgui.type_map.type2callback","title":"magicgui.type_map.type2callback(type_: type) -> list[ReturnCallback]","text":"

Return any callbacks that have been registered for type_.

Parameters:

Returns:

"},{"location":"api/widgets/","title":"Widget Index","text":"

Here you will find a list of all the widgets that are available in magicgui. Each widget has a link to its own documentation page, where you can find more information about the widget, including its parameters and events.

Widget Description CheckBox A checkbox with a text label. ComboBox A dropdown menu, allowing selection between multiple choices. Container A Widget to contain other widgets. DateEdit A widget for editing dates. DateTimeEdit A widget for editing dates and times. Dialog A modal container. EmptyWidget A base widget with no value. FileEdit A LineEdit widget with a button that opens a FileDialog. FloatRangeSlider A slider widget to adjust a range defined by two float values within a range. FloatSlider A slider widget to adjust an integer value within a range. FloatSpinBox A widget to edit a float with clickable up/down arrows. FunctionGui Wrapper for a container of widgets representing a callable object. Image A non-editable image display. Label A non-editable text display. LineEdit A one-line text editor. ListEdit A widget to represent a list of values. LiteralEvalLineEdit A one-line text editor that evaluates strings as python literals. LogSlider A slider widget to adjust a numerical value logarithmically within a range. MainFunctionGui Container of widgets as a Main Application Window. MainWindow A Widget to contain other widgets, includes a menu bar. Password A one-line text editor that obscures input. ProgressBar A progress bar widget. PushButton A clickable command button. QuantityEdit A combined LineEdit and ComboBox to edit a pint.Quantity. RadioButton A radio button with a text label. RadioButtons An exclusive group of radio buttons, providing a choice from multiple choices. RangeEdit A widget to represent a python range object, with start/stop/step. RangeSlider A slider widget to adjust a range between two integer values within a range. Select A list of options, allowing selection between multiple choices. SliceEdit A widget to represent slice objects, with start/stop/step. Slider A slider widget to adjust an integer value within a range. SpinBox A widget to edit an integer with clickable up/down arrows. Table A widget to represent columnar or 2D data with headers. TextEdit A widget to edit and display both plain and rich text. TimeEdit A widget for editing times. TupleEdit A widget to represent a tuple of values."},{"location":"api/widgets/CheckBox/","title":"CheckBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/CheckBox/#signals","title":"Signals","text":""},{"location":"api/widgets/CheckBox/#magicgui.widgets.CheckBox","title":"CheckBox","text":"

Bases: ButtonWidget

A checkbox with a text label.

Parameters:

"},{"location":"api/widgets/ComboBox/","title":"ComboBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/ComboBox/#signals","title":"Signals","text":""},{"location":"api/widgets/ComboBox/#magicgui.widgets.ComboBox","title":"ComboBox","text":"

Bases: CategoricalWidget

A dropdown menu, allowing selection between multiple choices.

Parameters:

"},{"location":"api/widgets/Container/","title":"Container","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Container/#signals","title":"Signals","text":""},{"location":"api/widgets/Container/#magicgui.widgets.Container","title":"Container","text":"

Bases: ContainerWidget[WidgetVar]

A Widget to contain other widgets.

Note that `Container` implements the\n[`typing.MutableSequence`][typing.MutableSequence]\ninterface, so you can use it like a list to add and remove widgets.\n

Parameters:

"},{"location":"api/widgets/DateEdit/","title":"DateEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/DateEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/DateEdit/#magicgui.widgets.DateEdit","title":"DateEdit","text":"

Bases: ValueWidget[date]

A widget for editing dates.

Parameters:

"},{"location":"api/widgets/DateTimeEdit/","title":"DateTimeEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/DateTimeEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/DateTimeEdit/#magicgui.widgets.DateTimeEdit","title":"DateTimeEdit","text":"

Bases: ValueWidget[datetime]

A widget for editing dates and times.

Parameters:

"},{"location":"api/widgets/Dialog/","title":"Dialog","text":"

Available in backends: qt

"},{"location":"api/widgets/Dialog/#signals","title":"Signals","text":""},{"location":"api/widgets/Dialog/#magicgui.widgets.Dialog","title":"Dialog","text":"

Bases: DialogWidget

A modal container.

Parameters:

"},{"location":"api/widgets/EmptyWidget/","title":"EmptyWidget","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/EmptyWidget/#signals","title":"Signals","text":""},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget","title":"EmptyWidget","text":"

Bases: ValueWidget

A base widget with no value.

This widget is primarily here to serve as a \"hidden widget\" to which a value or\ncallback can be bound.\n

Parameters:

"},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget.value","title":"value: Any property writable","text":"

Look for a bound value, otherwise fallback to get_value.

"},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget.__repr__","title":"__repr__() -> str","text":"

Return string repr (avoid looking for value).

"},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget.get_value","title":"get_value() -> Any","text":"

Return value if one has been manually set... otherwise return Param.empty.

"},{"location":"api/widgets/FileEdit/","title":"FileEdit","text":"

Available in backends:

"},{"location":"api/widgets/FileEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit","title":"FileEdit","text":"

Bases: Container

A LineEdit widget with a button that opens a FileDialog.

Parameters:

"},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit.mode","title":"mode: FileDialogMode property writable","text":"

Mode for the FileDialog.

"},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit.value","title":"value: tuple[Path, ...] | Path | None property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit.__repr__","title":"__repr__() -> str","text":"

Return string representation.

"},{"location":"api/widgets/FloatRangeSlider/","title":"FloatRangeSlider","text":"

Available in backends: qt

"},{"location":"api/widgets/FloatRangeSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/FloatRangeSlider/#magicgui.widgets.FloatRangeSlider","title":"FloatRangeSlider","text":"

Bases: MultiValuedSliderWidget

A slider widget to adjust a range defined by two float values within a range.

Parameters:

"},{"location":"api/widgets/FloatSlider/","title":"FloatSlider","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/FloatSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/FloatSlider/#magicgui.widgets.FloatSlider","title":"FloatSlider","text":"

Bases: SliderWidget[float]

A slider widget to adjust an integer value within a range.

Parameters:

"},{"location":"api/widgets/FloatSpinBox/","title":"FloatSpinBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/FloatSpinBox/#signals","title":"Signals","text":""},{"location":"api/widgets/FloatSpinBox/#magicgui.widgets.FloatSpinBox","title":"FloatSpinBox","text":"

Bases: RangedWidget[float]

A widget to edit a float with clickable up/down arrows.

Parameters:

"},{"location":"api/widgets/FunctionGui/","title":"FunctionGui","text":"

Available in backends:

"},{"location":"api/widgets/FunctionGui/#signals","title":"Signals","text":""},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui","title":"FunctionGui","text":"

Bases: Container, Generic[_P, _R]

Wrapper for a container of widgets representing a callable object.

Parameters:

Raises:

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__signature__","title":"__signature__: MagicSignature property","text":"

Return a MagicSignature object representing the current state of the gui.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.call_button","title":"call_button: PushButton | None property","text":"

Return the call button.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.call_count","title":"call_count: int property","text":"

Return the number of times the function has been called.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.result_name","title":"result_name: str property writable","text":"

Return a name that can be used for the result of this magicfunction.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.return_annotation","title":"return_annotation: Any property","text":"

Return annotation for inspect.Signature conversion.

ForwardRefs will be resolve when setting the annotation.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__call__","title":"__call__(*args: _P.args, **kwargs: _P.kwargs) -> _R","text":"

Call the original function with the current parameter values from the Gui.

You may pass a update_widget=True keyword argument to update the widget values to match the current parameter values before calling the function.

It is also possible to override the current parameter values from the GUI by providing args/kwargs to the function call. Only those provided will override the ones from the gui. A called signal will also be emitted with the results.

Returns:

Examples:

gui = FunctionGui(func, show=True)\n\n# then change parameters in the gui, or by setting:  gui.param.value = something\n\ngui()  # calls the original function with the current parameters\n
"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__get__","title":"__get__(obj: object, objtype: type | None = None) -> FunctionGui","text":"

Provide descriptor protocol.

This allows the @magicgui decorator to work on a function as well as a method. If a method on a class is decorated with @magicgui, then accessing the attribute on an instance of that class will return a version of the FunctionGui in which the first argument of the function is bound to the instance. (Just like what you'd expect with the @property decorator.)

Returns:

Examples:

>>> class MyClass:\n...     @magicgui\n...     def my_method(self, x=1):\n...         print(locals())\n...\n>>> c = MyClass()\n>>> c.my_method  # the FunctionGui that can be used as a widget\n\n# calling it works as usual, with `c` provided as `self`\n>>> c.my_method(x=34)\n{'self': <__main__.MyClass object at 0x7fb610e455e0>, 'x': 34}\n
"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__init__","title":"__init__(function: Callable[_P, _R], call_button: bool | str | None = None, layout: str = 'vertical', scrollable: bool = False, labels: bool = True, tooltips: bool = True, app: AppRef | None = None, visible: bool | None = None, auto_call: bool = False, result_widget: bool = False, param_options: dict[str, dict] | None = None, name: str | None = None, persist: bool = False, raise_on_unknown: bool = False, **kwargs: Any)","text":""},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__repr__","title":"__repr__() -> str","text":"

Return string representation of instance.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__set__","title":"__set__(obj: Any, value: Any) -> NoReturn","text":"

Prevent setting a magicgui attribute.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.copy","title":"copy() -> FunctionGui","text":"

Return a copy of this FunctionGui.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.reset_call_count","title":"reset_call_count() -> None","text":"

Reset the call count to 0.

"},{"location":"api/widgets/Image/","title":"Image","text":"

Available in backends: qt

"},{"location":"api/widgets/Image/#signals","title":"Signals","text":""},{"location":"api/widgets/Image/#magicgui.widgets.Image","title":"Image","text":"

Bases: ValueWidget

A non-editable image display.

Parameters:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.image_data","title":"image_data: np.ndarray | None property","text":"

Return image data.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.image_rgba","title":"image_rgba: np.ndarray | None property","text":"

Return rendered numpy array.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.value","title":"value property writable","text":"

Return current image array.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.__repr__","title":"__repr__() -> str","text":"

Return representation of widget of instance.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.get_clim","title":"get_clim() -> tuple[float | None, float | None]","text":"

Get contrast limits (for monochromatic images).

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.scale_widget_to_image_size","title":"scale_widget_to_image_size()","text":"

Set the size of the widget to the size of the image.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_clim","title":"set_clim(vmin: float | None = None, vmax: float | None = None)","text":"

Set contrast limits (for monochromatic images).

Parameters:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_cmap","title":"set_cmap(cmap: str | Colormap | matplotlib.colors.Colormap)","text":"

Set colormap (for monochromatic images).

Parameters:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_data","title":"set_data(val: str | Path | np.ndarray | PIL.Image.Image, cmap: str | Colormap | matplotlib.colors.Colormap | None = None, norm: _mpl_image.Normalize | matplotlib.colors.Normalize | None = None, vmin: float | None = None, vmax: float | None = None, width: int | Literal['auto'] | None = None, height: int | Literal['auto'] | None = None, format: str | None = None)","text":"

Set image data with various optional display parameters.

Parameters:

Raises:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_norm","title":"set_norm(norm: Normalize | matplotlib.colors.Normalize)","text":"

Set normalization method.

Parameters:

"},{"location":"api/widgets/Label/","title":"Label","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Label/#signals","title":"Signals","text":""},{"location":"api/widgets/Label/#magicgui.widgets.Label","title":"Label","text":"

Bases: ValueWidget[str]

A non-editable text display.

Parameters:

"},{"location":"api/widgets/LineEdit/","title":"LineEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/LineEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/LineEdit/#magicgui.widgets.LineEdit","title":"LineEdit","text":"

Bases: ValueWidget[str]

A one-line text editor.

Parameters:

"},{"location":"api/widgets/ListEdit/","title":"ListEdit","text":"

Available in backends:

"},{"location":"api/widgets/ListEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit","title":"ListEdit","text":"

Bases: Container[ValueWidget[_V]]

A widget to represent a list of values.

A ListEdit container can create a list with multiple objects of same type. It\nwill contain many child widgets and their value is represented as a Python list\nobject. If a list is given as the initial value, types of child widgets are\ndetermined from the contents. Number of contents can be adjusted with +/-\nbuttons.\n

Parameters:

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation. For ListEdit, annotation will be like 'list[str]'.

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.data","title":"data: ListDataView[_V] property writable","text":"

Return a data view of current value.

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.value","title":"value: list[_V] property writable","text":"

Return current value as a list object.

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.__delitem__","title":"__delitem__(key: int | slice) -> None","text":"

Delete child widget(s).

"},{"location":"api/widgets/LiteralEvalLineEdit/","title":"LiteralEvalLineEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/LiteralEvalLineEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/LiteralEvalLineEdit/#magicgui.widgets.LiteralEvalLineEdit","title":"LiteralEvalLineEdit","text":"

Bases: ValueWidget[str]

A one-line text editor that evaluates strings as python literals.

Parameters:

"},{"location":"api/widgets/LogSlider/","title":"LogSlider","text":"

Available in backends:

"},{"location":"api/widgets/LogSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/LogSlider/#magicgui.widgets.LogSlider","title":"LogSlider","text":"

Bases: TransformedRangedWidget

A slider widget to adjust a numerical value logarithmically within a range.

Parameters:

"},{"location":"api/widgets/LogSlider/#magicgui.widgets.LogSlider.base","title":"base: float property writable","text":"

Return base used for the log.

"},{"location":"api/widgets/LogSlider/#magicgui.widgets.LogSlider.tracking","title":"tracking: bool property writable","text":"

Return whether slider tracking is enabled.

If tracking is enabled (the default), the slider emits the changed() signal while the slider is being dragged. If tracking is disabled, the slider emits the changed() signal only when the user releases the slider.

"},{"location":"api/widgets/MainFunctionGui/","title":"MainFunctionGui","text":"

Available in backends:

"},{"location":"api/widgets/MainFunctionGui/#signals","title":"Signals","text":""},{"location":"api/widgets/MainFunctionGui/#magicgui.widgets.MainFunctionGui","title":"MainFunctionGui","text":"

Bases: FunctionGui[_P, _R], MainWindow

Container of widgets as a Main Application Window.

"},{"location":"api/widgets/MainWindow/","title":"MainWindow","text":"

Available in backends: qt

"},{"location":"api/widgets/MainWindow/#signals","title":"Signals","text":""},{"location":"api/widgets/MainWindow/#magicgui.widgets.MainWindow","title":"MainWindow","text":"

Bases: MainWindowWidget

A Widget to contain other widgets, includes a menu bar.

Parameters:

"},{"location":"api/widgets/Password/","title":"Password","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Password/#signals","title":"Signals","text":""},{"location":"api/widgets/Password/#magicgui.widgets.Password","title":"Password","text":"

Bases: ValueWidget[str]

A one-line text editor that obscures input.

Parameters:

"},{"location":"api/widgets/ProgressBar/","title":"ProgressBar","text":"

Available in backends: qt

"},{"location":"api/widgets/ProgressBar/#signals","title":"Signals","text":""},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar","title":"ProgressBar","text":"

Bases: SliderWidget[float]

A progress bar widget.

Parameters:

"},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar.step","title":"step: float property writable","text":"

Step size for widget values.

"},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar.decrement","title":"decrement(val: float | None = None) -> None","text":"

Decrease current value by step size, or provided value.

"},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar.increment","title":"increment(val: float | None = None) -> None","text":"

Increase current value by step size, or provided value.

"},{"location":"api/widgets/PushButton/","title":"PushButton","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/PushButton/#signals","title":"Signals","text":""},{"location":"api/widgets/PushButton/#magicgui.widgets.PushButton","title":"PushButton","text":"

Bases: ButtonWidget

A clickable command button.

Parameters:

"},{"location":"api/widgets/QuantityEdit/","title":"QuantityEdit","text":"

Available in backends: qt

"},{"location":"api/widgets/QuantityEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/QuantityEdit/#magicgui.widgets.QuantityEdit","title":"QuantityEdit","text":"

Bases: ValueWidget

A combined LineEdit and ComboBox to edit a pint.Quantity.

Parameters:

"},{"location":"api/widgets/RadioButton/","title":"RadioButton","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/RadioButton/#signals","title":"Signals","text":""},{"location":"api/widgets/RadioButton/#magicgui.widgets.RadioButton","title":"RadioButton","text":"

Bases: ButtonWidget

A radio button with a text label.

Parameters:

"},{"location":"api/widgets/RadioButtons/","title":"RadioButtons","text":"

Available in backends: qt

"},{"location":"api/widgets/RadioButtons/#signals","title":"Signals","text":""},{"location":"api/widgets/RadioButtons/#magicgui.widgets.RadioButtons","title":"RadioButtons","text":"

Bases: CategoricalWidget, _OrientationMixin

An exclusive group of radio buttons, providing a choice from multiple choices.

Parameters:

"},{"location":"api/widgets/RangeEdit/","title":"RangeEdit","text":"

Available in backends:

"},{"location":"api/widgets/RangeEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/RangeEdit/#magicgui.widgets.RangeEdit","title":"RangeEdit","text":"

Bases: Container[SpinBox]

A widget to represent a python range object, with start/stop/step.

A range object produces a sequence of integers from start (inclusive)\nto stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.\nstart defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.\nThese are exactly the valid indices for a list of 4 elements.\nWhen step is given, it specifies the increment (or decrement).\n

Parameters:

"},{"location":"api/widgets/RangeEdit/#magicgui.widgets.RangeEdit.value","title":"value: range property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/RangeEdit/#magicgui.widgets.RangeEdit.__repr__","title":"__repr__() -> str","text":"

Return string representation.

"},{"location":"api/widgets/RangeSlider/","title":"RangeSlider","text":"

Available in backends: qt

"},{"location":"api/widgets/RangeSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/RangeSlider/#magicgui.widgets.RangeSlider","title":"RangeSlider","text":"

Bases: MultiValuedSliderWidget

A slider widget to adjust a range between two integer values within a range.

Parameters:

"},{"location":"api/widgets/Select/","title":"Select","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Select/#signals","title":"Signals","text":""},{"location":"api/widgets/Select/#magicgui.widgets.Select","title":"Select","text":"

Bases: CategoricalWidget

A list of options, allowing selection between multiple choices.

Parameters:

"},{"location":"api/widgets/SliceEdit/","title":"SliceEdit","text":"

Available in backends:

"},{"location":"api/widgets/SliceEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/SliceEdit/#magicgui.widgets.SliceEdit","title":"SliceEdit","text":"

Bases: RangeEdit

A widget to represent slice objects, with start/stop/step.

slice(stop) slice(start, stop[, step])

Slice objects may be used for extended slicing (e.g. a[0:10:2])

"},{"location":"api/widgets/SliceEdit/#magicgui.widgets.SliceEdit.value","title":"value: slice property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/Slider/","title":"Slider","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Slider/#signals","title":"Signals","text":""},{"location":"api/widgets/Slider/#magicgui.widgets.Slider","title":"Slider","text":"

Bases: SliderWidget[int]

A slider widget to adjust an integer value within a range.

Parameters:

"},{"location":"api/widgets/SpinBox/","title":"SpinBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/SpinBox/#signals","title":"Signals","text":""},{"location":"api/widgets/SpinBox/#magicgui.widgets.SpinBox","title":"SpinBox","text":"

Bases: RangedWidget[int]

A widget to edit an integer with clickable up/down arrows.

Parameters:

"},{"location":"api/widgets/Table/","title":"Table","text":"

Available in backends: qt

"},{"location":"api/widgets/Table/#signals","title":"Signals","text":""},{"location":"api/widgets/Table/#magicgui.widgets.Table","title":"Table","text":"

Bases: ValueWidget, _ReadOnlyMixin, MutableMapping[TblKey, list]

A widget to represent columnar or 2D data with headers.

Tables behave like plain dicts, where the keys are column headers and the (list-like) values are column data.

Parameters:

index : Collection, optional A sized iterable container of row headers. By default, row headers will be tuple(range(len(data))). Values provided here override any implied in value. columns : Collection, optional A sized iterable container of column headers. By default, column headers will be tuple(range(len(data[0]))). Values provided here override any implied in value. **kwargs Additional kwargs will be passed to the magicgui.widgets.Widget constructor.

Attributes:

Methods:

"},{"location":"api/widgets/Table/#magicgui.widgets.Table--events","title":"Events","text":"

changed Emitted whenever a cell in the table changes. The value will have a dict of information regarding the cell that changed: {'data': x, 'row': int, 'column': int, 'column_header': str, 'row_header': str} CURRENTLY: only emitted on changes in the GUI. not programmatic changes.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.column_headers","title":"column_headers: tuple property writable","text":"

Return column headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.data","title":"data: DataView property writable","text":"

Return DataView object for this table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.row_headers","title":"row_headers: tuple property writable","text":"

Return row headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.shape","title":"shape: tuple[int, int] property","text":"

Return shape of table widget (rows, cols).

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.size","title":"size: int property","text":"

Return shape of table widget (rows, cols).

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.value","title":"value: dict[TblKey, Collection] property writable","text":"

Return dict with current data, index, and columns of the widget.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__delitem__","title":"__delitem__(key: TblKey) -> None","text":"

Delete a column from the table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__getitem__","title":"__getitem__(key: TblKey) -> list","text":"

Get a column from the table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__hash__","title":"__hash__() -> int","text":"

Make table hashable.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__iter__","title":"__iter__() -> Iterator","text":"

Yield column headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__len__","title":"__len__() -> int","text":"

Return number of columns.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__new__","title":"__new__(value: TableData | None = None, *, index: Collection | None = None, columns: Collection | None = None, **kwargs: Any) -> Table","text":"

Just for the signature.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__repr__","title":"__repr__() -> str","text":"

Return string repr.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__setitem__","title":"__setitem__(key: TblKey, v: Collection) -> None","text":"

Set a column in the table. If k doesn't exist, make a new column.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.clear","title":"clear() -> None","text":"

Clear the table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.items","title":"items(axis: str = 'column') -> TableItemsView[TblKey, list]","text":"

Return a set-like object providing a view on this table's items.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.keys","title":"keys(axis: str = 'column') -> HeadersView[TblKey]","text":"

Return a set-like object providing a view on this table's headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.to_dataframe","title":"to_dataframe() -> pandas.DataFrame","text":"

Convert TableData to dataframe.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.to_dict","title":"to_dict(orient: str = 'dict') -> list | dict","text":"

Convert the Table to a dictionary.

The type of the key-value pairs can be customized with the parameters (see below).

Parameters:

"},{"location":"api/widgets/TextEdit/","title":"TextEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/TextEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/TextEdit/#magicgui.widgets.TextEdit","title":"TextEdit","text":"

Bases: ValueWidget[str], _ReadOnlyMixin

A widget to edit and display both plain and rich text.

Parameters:

"},{"location":"api/widgets/TimeEdit/","title":"TimeEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/TimeEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/TimeEdit/#magicgui.widgets.TimeEdit","title":"TimeEdit","text":"

Bases: ValueWidget[TV]

A widget for editing times.

Parameters:

"},{"location":"api/widgets/TupleEdit/","title":"TupleEdit","text":"

Available in backends:

"},{"location":"api/widgets/TupleEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/TupleEdit/#magicgui.widgets.TupleEdit","title":"TupleEdit","text":"

Bases: Container[ValueWidget]

A widget to represent a tuple of values.

A TupleEdit container has several child widgets of different type. Their value is\nrepresented as a Python tuple object. If a tuple is given as the initial value,\ntypes of child widgets are determined one by one. Unlike ListEdit, number of\ncontents is not editable.\n

Parameters:

"},{"location":"api/widgets/TupleEdit/#magicgui.widgets.TupleEdit.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation. For TupleEdit, annotation will be like 'tuple[str, int]'.

"},{"location":"api/widgets/TupleEdit/#magicgui.widgets.TupleEdit.value","title":"value: tuple property writable","text":"

Return current value as a tuple.

"},{"location":"api/widgets/bases/","title":"magicgui.widgets.bases","text":"

The magicgui.widgets.bases module contains the base classes for all widgets.

While most users will never instantiate these classes directly, the methods and properties of these classes are inherited by all widgets, and define the common API for all widgets. Therefore, it is worth being aware of the type of widget you are working with.

"},{"location":"api/widgets/bases/#summary","title":"Summary","text":"Widget Description Widget Basic Widget, wrapping a class that implements WidgetProtocol. ButtonWidget Widget with a value, Wraps a widget implementing the ButtonWidgetProtocol. CategoricalWidget Widget with a value and choices. Wraps CategoricalWidgetProtocol. ContainerWidget Widget that can contain other widgets. DialogWidget Modal Container. MainWindowWidget Top level Application widget that can contain other widgets. RangedWidget Widget with a constrained value. Wraps RangedWidgetProtocol. SliderWidget Widget with a constrained value and orientation. Wraps SliderWidgetProtocol. ValueWidget Widget with a value, Wraps ValueWidgetProtocol."},{"location":"api/widgets/bases/#class-hierarchy","title":"Class Hierarchy","text":"

In visual form, the widget class hierarchy looks like this:

classDiagram\n    Widget <|-- ValueWidget\n    Widget <|-- ContainerWidget\n    BackendWidget ..|> WidgetProtocol : implements a\n    ValueWidget <|-- RangedWidget\n    ValueWidget <|-- ButtonWidget\n    ValueWidget <|-- CategoricalWidget\n    RangedWidget <|-- SliderWidget\n    Widget --* WidgetProtocol : controls a\n    <<Interface>> WidgetProtocol\n    class WidgetProtocol {\n        _mgui_get_X()\n        _mgui_set_X()\n    }\n    class Widget{\n        name: str\n        annotation: Any\n        label: str\n        tooltip: str\n        visible: bool\n        enabled: bool\n        native: Any\n        height: int\n        width: int\n        hide()\n        show()\n        close()\n        render()\n    }\n    class ValueWidget{\n        value: Any\n        changed: SignalInstance\n        bind(value, call) Any\n        unbind()\n    }\n    class RangedWidget{\n        value: float | tuple\n        min: float\n        max: float\n        step: float\n        adaptive_step: bool\n        range: tuple[float, float]\n    }\n    class SliderWidget{\n        orientation: str\n    }\n    class ButtonWidget{\n        value: bool\n        clicked: SignalInstance\n        text: str\n    }\n    class CategoricalWidget{\n        choices: List[Any]\n    }\n    class ContainerWidget{\n        widgets: List[Widget]\n        labels: bool\n        layout: str\n        margins: tuple[int, int, int, int]\n        reset_choices()\n        asdict() Dict[str, Any]\n        update(mapping)\n    }\n\n    click Widget href \"#magicgui.widgets.bases.Widget\"\n    click ValueWidget href \"#magicgui.widgets.bases.ValueWidget\"\n    click RangedWidget href \"#magicgui.widgets.bases.RangedWidget\"\n    click SliderWidget href \"#magicgui.widgets.bases.SliderWidget\"\n    click ButtonWidget href \"#magicgui.widgets.bases.ButtonWidget\"\n    click CategoricalWidget href \"#magicgui.widgets.bases.CategoricalWidget\"\n    click ContainerWidget href \"#magicgui.widgets.bases.ContainerWidget\"\n
"},{"location":"api/widgets/bases/#base-widget-classes","title":"Base Widget Classes","text":""},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget","title":"magicgui.widgets.bases.Widget","text":"

Basic Widget, wrapping a class that implements WidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.enabled","title":"enabled: bool property writable","text":"

Whether widget is enabled (editable).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.height","title":"height: int property writable","text":"

Return the current height of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.label","title":"label: str property writable","text":"

Return a label to use for this widget when present in Containers.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.max_height","title":"max_height: int property writable","text":"

Get the maximum height of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.max_width","title":"max_width: int property writable","text":"

Get the maximum width of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.min_height","title":"min_height: int property writable","text":"

Get the minimum height of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.min_width","title":"min_width: int property writable","text":"

Get the minimum width of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.native","title":"native: Any property","text":"

Return native backend widget.

Note this is the widget that contains the layout, and not any parent widgets of this (e.g. a parent widget that is used to enable scroll bars)

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.param_kind","title":"param_kind: inspect._ParameterKind property writable","text":"

Return :attr:inspect.Parameter.kind represented by this widget.

Used in building signatures from multiple widgets, by default :attr:~inspect.Parameter.POSITIONAL_OR_KEYWORD

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.parent","title":"parent: Widget property writable","text":"

Return the parent widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.root_native_widget","title":"root_native_widget: Any property","text":"

Return the root native backend widget.

This can be different from the .native widget if the layout is a child of some other widget, e.g. a widget used to enable scroll bars.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.tooltip","title":"tooltip: str | None property writable","text":"

Get the tooltip for this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.visible","title":"visible: bool property writable","text":"

Return whether widget is visible.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.widget_type","title":"widget_type: str property","text":"

Return type of widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.width","title":"width: int property writable","text":"

Return the current width of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.__repr__","title":"__repr__() -> str","text":"

Return representation of widget of instance.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.close","title":"close() -> None","text":"

Close widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.hide","title":"hide() -> None","text":"

Hide widget.

alias for widget.visible = False

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.render","title":"render() -> np.ndarray","text":"

Return an RGBA (MxNx4) numpy array bitmap of the rendered widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.show","title":"show(run: bool = False) -> Widget","text":"

Show widget.

alias for widget.visible = True

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.shown","title":"shown() -> Iterator[Application]","text":"

Context manager to show the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget","title":"magicgui.widgets.bases.ButtonWidget","text":"

Bases: ValueWidget[bool]

Widget with a value, Wraps a widget implementing the ButtonWidgetProtocol.

see ButtonWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget.clicked","title":"clicked: SignalInstance property","text":"

Alias for changed event.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget.text","title":"text: str property writable","text":"

Text of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget","title":"magicgui.widgets.bases.CategoricalWidget","text":"

Bases: ValueWidget[T]

Widget with a value and choices. Wraps CategoricalWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.choices","title":"choices: tuple[T | None, ...] property writable","text":"

Available value choices for this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.current_choice","title":"current_choice: str property","text":"

Return the text of the currently selected choice.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.value","title":"value: T property writable","text":"

Return current value of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.__len__","title":"__len__() -> int","text":"

Return the number of choices.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.del_choice","title":"del_choice(choice_name: str) -> None","text":"

Delete the provided choice_name and associated data.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.get_choice","title":"get_choice(choice_name: str) -> T","text":"

Get data for the provided choice_name.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.reset_choices","title":"reset_choices(*_: Any) -> None","text":"

Reset choices to the default state.

If self._default_choices is a callable, this may NOT be the exact same set of choices as when the widget was instantiated, if the callable relies on external state.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.set_choice","title":"set_choice(choice_name: str, data: Any | None = None) -> None","text":"

Set data for the provided choice_name.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget","title":"magicgui.widgets.bases.ContainerWidget","text":"

Bases: Widget, _OrientationMixin, MutableSequence[WidgetVar]

Widget that can contain other widgets.

Wraps a widget that implements ContainerProtocol.

A ContainerWidget behaves like a python list of Widget objects. Subwidgets can be accessed using integer or slice-based indexing (container[0]), as well as by widget name (container.<widget_name>). Widgets can be added with append or insert, and removed with del or pop, etc...

There is a tight connection between a ContainerWidget and an inspect.Signature object, just as there is a tight connection between individual Widgetobjects an an :class:inspect.Parameter object. The signature representation of a ContainerWidget (with the current settings as default values) is accessible with the :meth:~ContainerWidget.__signature__ method (or by using :func:inspect.signature from the standard library)

For a ContainerWidget subclass that is tightly coupled to a specific function signature (as in the \"classic\" magicgui decorator), see magicgui.widgets.FunctionGui.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__signature__","title":"__signature__: MagicSignature property","text":"

Return a MagicSignature object representing the current state of the gui.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.labels","title":"labels: bool property writable","text":"

Whether widgets are presented with labels.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.layout","title":"layout: str property writable","text":"

Return the layout of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.margins","title":"margins: tuple[int, int, int, int] property writable","text":"

Return margin between the content and edges of the container.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__delattr__","title":"__delattr__(name: str) -> None","text":"

Delete a widget by name.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__delitem__","title":"__delitem__(key: int | slice) -> None","text":"

Delete a widget by integer or slice index.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__dir__","title":"__dir__() -> list[str]","text":"

Add subwidget names to the dir() call for this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__getattr__","title":"__getattr__(name: str) -> WidgetVar","text":"

Return attribute name. Will return a widget if present.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__getitem__","title":"__getitem__(key: int | str | slice) -> WidgetVar | MutableSequence[WidgetVar]","text":"

Get item by integer, str, or slice.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__len__","title":"__len__() -> int","text":"

Return the count of widgets.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__repr__","title":"__repr__() -> str","text":"

Return a repr.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__setattr__","title":"__setattr__(name: str, value: Any) -> None","text":"

Set attribute name. Prevents changing widget if present, (use del).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__setitem__","title":"__setitem__(key: Any, value: Any) -> NoReturn","text":"

Prevent assignment by index.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.asdict","title":"asdict() -> dict[str, Any]","text":"

Return state of widget as dict.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.from_callable","title":"from_callable(obj: Callable, gui_options: dict | None = None, **kwargs: Unpack[ContainerKwargs]) -> Container classmethod","text":"

Create a Container widget from a callable object.

In most cases, it will be preferable to create a FunctionGui instead.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.from_signature","title":"from_signature(sig: inspect.Signature, **kwargs: Unpack[ContainerKwargs]) -> Container classmethod","text":"

Create a Container widget from an inspect.Signature object.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.index","title":"index(value: Any, start: int = 0, stop: int = 9223372036854775807) -> int","text":"

Return index of a specific widget instance (or widget name).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.insert","title":"insert(key: int, widget: WidgetVar) -> None","text":"

Insert widget at key.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.remove","title":"remove(value: Widget | str) -> None","text":"

Remove a widget instance (may also be string name of widget).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.reset_choices","title":"reset_choices(*_: Any) -> None","text":"

Reset choices for all Categorical subWidgets to the default state.

If widget._default_choices is a callable, this may NOT be the exact same set of choices as when the widget was instantiated, if the callable relies on external state.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.update","title":"update(mapping: Mapping | Iterable[tuple[str, Any]] | None = None, **kwargs: Any) -> None","text":"

Update the parameters in the widget from a mapping, iterable, or kwargs.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.DialogWidget","title":"magicgui.widgets.bases.DialogWidget","text":"

Bases: ContainerWidget

Modal Container.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.DialogWidget.exec","title":"exec() -> bool","text":"

Show the dialog, and block.

Return True if the dialog was accepted, False if rejected.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.MainWindowWidget","title":"magicgui.widgets.bases.MainWindowWidget","text":"

Bases: ContainerWidget

Top level Application widget that can contain other widgets.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.MainWindowWidget.create_menu_item","title":"create_menu_item(menu_name: str, item_name: str, callback: Callable | None = None, shortcut: str | None = None) -> None","text":"

Create a menu item item_name under menu menu_name.

menu_name will be created if it does not already exist.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget","title":"magicgui.widgets.bases.RangedWidget","text":"

Bases: ValueWidget[T]

Widget with a constrained value. Wraps RangedWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.adaptive_step","title":"adaptive_step: bool property writable","text":"

Whether the step size is adaptive.

Adaptive decimal step means that the step size will continuously be adjusted to one power of ten below the current value. So when the value is 1100, the step is set to 100, so stepping up once increases it to 1200. For 1200 stepping up takes it to 1300. For negative values, stepping down from -1100 goes to -1200.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.max","title":"max: float property writable","text":"

Maximum allowable value for the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.min","title":"min: float property writable","text":"

Minimum allowable value for the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.range","title":"range: tuple[float, float] property writable","text":"

Range of allowable values for the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.step","title":"step: float | None property writable","text":"

Step size for widget values (None if adaptive step is turned on).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.value","title":"value(value: T) -> None","text":"

Set widget value, will raise Value error if not within min/max.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget","title":"magicgui.widgets.bases.SliderWidget","text":"

Bases: RangedWidget[T], _OrientationMixin

Widget with a constrained value and orientation. Wraps SliderWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget.readout","title":"readout: bool property writable","text":"

Get visibility state of readout widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget.tracking","title":"tracking: bool property writable","text":"

Return whether slider tracking is enabled.

If tracking is enabled (the default), the slider emits the changed() signal while the slider is being dragged. If tracking is disabled, the slider emits the changed() signal only when the user releases the slider.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget","title":"magicgui.widgets.bases.ValueWidget","text":"

Bases: Widget, Generic[T]

Widget with a value, Wraps ValueWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation. If the widget is nullable (had a type annototation of Optional[Type]), annotation will return the first argument in the Optional clause.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.value","title":"value: T property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.__repr__","title":"__repr__() -> str","text":"

Return representation of widget of instance.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.bind","title":"bind(value: T | Callable[[ValueWidget], T], call: bool = True) -> None","text":"

Binds value to self.value.

If a value is bound to this widget, then whenever widget.value is accessed, the value provided here will be returned. value can be a callable, in which case value(self) will be returned (i.e. your callback must accept a single parameter, which is this widget instance.).

If you provide a callable and you don't want it to be called (but rather just returned as a callable object, then use call=False when binding your value.

Note: if you need to access the \"original\" widget.value within your callback, please use widget.get_value() instead of the widget.value property, in order to avoid a RuntimeError.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.get_value","title":"get_value() -> T","text":"

Callable version of self.value.

The main API is to use self.value, however, this is here in order to provide an escape hatch if trying to access the widget's value inside of a callback bound to self._bound_value.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.unbind","title":"unbind() -> None","text":"

Unbinds any bound values. (see ValueWidget.bind).

"},{"location":"api/widgets/create_widget/","title":"magicgui.widgets.create_widget","text":""},{"location":"api/widgets/create_widget/#magicgui.widgets.create_widget","title":"magicgui.widgets.create_widget(value=Undefined, annotation=None, name='', param_kind='POSITIONAL_OR_KEYWORD', label=None, gui_only=False, app=None, widget_type=None, options=None, is_result=False, raise_on_unknown=True)","text":"

Create and return appropriate widget subclass.

This factory function can be used to create a widget appropriate for the provided value and/or annotation provided. See Type Mapping Docs for details on how the widget type is determined from type annotations.

Parameters:

Returns:

Raises:

Examples:

from magicgui.widgets import create_widget\n\n# create a widget from a string value\nwdg = create_widget(value=\"hello world\")\nassert wdg.value == \"hello world\"\n\n# create a widget from a string annotation\nwdg = create_widget(annotation=str)\nassert wdg.value == \"\"\n
"},{"location":"generated_examples/","title":"Examples","text":""},{"location":"generated_examples/#getting-started","title":"Getting started","text":"

A gallery of examples for magicgui.

Basic example

Basic widgets demo

"},{"location":"generated_examples/#demo-applications","title":"Demo applications","text":"

Example applications built with magicgui.

Input values dialog

Quantities with pint

Callable functions demo

Snell's law demonstration using magicgui

Hotdog or not app

Chaining functions together

"},{"location":"generated_examples/#demo-widget-types","title":"Demo widget types","text":"

Example gallery demonstrating the available widget types in magicgui.

Image widget

Custom text labels for widgets

Range slider widget

Log slider widget

Optional user choice

Multiple selection widget

Password login

File dialog widget

Dropdown selection widget

Table widget

"},{"location":"generated_examples/#matplotlib-and-magicgui","title":"matplotlib and magicgui","text":"

Examples involving matplotlib graphs and magicgui.

matplotlib figure example

Waveforms example

"},{"location":"generated_examples/#napari-and-magicgui","title":"napari and magicgui","text":"

Examples integrating magicgui with napari.

napari forward reference demo

napari Qt demo

napari parameter sweeps

napari image arithmetic widget

"},{"location":"generated_examples/#jupyter-notebooks-and-magicgui","title":"Jupyter notebooks and magicgui","text":"

Examples using jupyter notebooks together with magicgui.

Jupyter notebooks and magicgui

"},{"location":"generated_examples/#progress-bar-examples","title":"Progress bar examples","text":"

Examples of progress bars in magicgui.

Manual progress bar

Simple progress bar

Indeterminate progress bar

Nested progress bars

"},{"location":"generated_examples/#under-the-hood","title":"Under the hood","text":"

Learn more advanced usage patterns for magicgui, including self referencing widgets and decorating class methods with magicgui.

Self reference magicgui widgets

Deocrate class methods with magicgui

Download all examples in Python source code: generated_examples_python.zip

Download all examples in Jupyter notebooks: generated_examples_jupyter.zip

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/basic_example/","title":"Basic example","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/basic_example/#basic-example","title":"Basic example","text":"

A basic example using magicgui.

Out:

<FunctionGui example(x: int = 0, y='hi')>\n

from magicgui import magicgui\n\n\n@magicgui\ndef example(x: int, y=\"hi\"):\n    \"\"\"Basic example function.\"\"\"\n    return x, y\n\n\nexample.changed.connect(print)\nexample.show(run=True)\n

Total running time of the script: ( 0 minutes 1.469 seconds)

Download Python source code: basic_example.py

Download Jupyter notebook: basic_example.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/basic_widgets_demo/","title":"Basic widgets demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/basic_widgets_demo/#basic-widgets-demo","title":"Basic widgets demo","text":"

Widget demonstration with magicgui.

This code demonstrates a few of the widget types that magicgui can create based on the parameter types in your function.

Out:

<MainFunctionGui widget_demo(boolean=True, integer=1, spin_float=3.14, slider_float=43.5, slider_int=550, string='Text goes here', dropdown=<Medium.Glass: 1.52>, radio_option=2, date=datetime.date(1999, 12, 31), time=datetime.time(1, 30, 20), datetime=datetime.datetime(2023, 10, 11, 11, 39, 57, 413000), filename=PosixPath('/Users/runner'))>\n

import datetime\nfrom enum import Enum\nfrom pathlib import Path\n\nfrom magicgui import magicgui\n\n\nclass Medium(Enum):\n    \"\"\"Enum for various media and their refractive indices.\"\"\"\n\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(\n    main_window=True,\n    call_button=\"Calculate\",\n    layout=\"vertical\",\n    result_widget=True,\n    slider_float={\"widget_type\": \"FloatSlider\", \"max\": 100},\n    slider_int={\"widget_type\": \"Slider\", \"readout\": False},\n    radio_option={\n        \"widget_type\": \"RadioButtons\",\n        \"orientation\": \"horizontal\",\n        \"choices\": [(\"first option\", 1), (\"second option\", 2)],\n    },\n    filename={\"label\": \"Pick a file:\"},\n)\ndef widget_demo(\n    boolean=True,\n    integer=1,\n    spin_float=3.14159,\n    slider_float=43.5,\n    slider_int=550,\n    string=\"Text goes here\",\n    dropdown=Medium.Glass,\n    radio_option=2,\n    date=datetime.date(1999, 12, 31),\n    time=datetime.time(1, 30, 20),\n    datetime=datetime.datetime.now(),\n    filename=Path.home(),\n):\n    \"\"\"We can use numpy docstrings to provide tooltips.\n\n    Parameters\n    ----------\n    boolean : bool, optional\n        A checkbox for booleans, by default True\n    integer : int, optional\n        Some integer, by default 1\n    spin_float : float, optional\n        This one is a float, by default \"pi\"\n    slider_float : float, optional\n        Hey look! I'm a slider, by default 43.5\n    slider_int : float, optional\n        I only take integers, and I've hidden my readout, by default 550\n    string : str, optional\n        We'll use this string carefully, by default \"Text goes here\"\n    dropdown : Enum, optional\n        Pick a medium, by default Medium.Glass\n    radio_option : int\n        A set of radio buttons.\n    date : datetime.date, optional\n        Your birthday, by default datetime.date(1999, 12, 31)\n    time : datetime.time, optional\n        Some time, by default datetime.time(1, 30, 20)\n    datetime : datetime.datetime, optional\n        A very specific time and date, by default ``datetime.datetime.now()``\n    filename : str, optional\n        Pick a path, by default Path.home()\n    \"\"\"\n    return locals().values()\n\n\nwidget_demo.changed.connect(print)\nwidget_demo.show(run=True)\n

Total running time of the script: ( 0 minutes 0.283 seconds)

Download Python source code: basic_widgets_demo.py

Download Jupyter notebook: basic_widgets_demo.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/mg_execution_times/","title":"Computation times","text":"

00:01.752 total execution time for generated_examples files:

+-------------------------------------------------------------------------------------+-----------+--------+ | basic_example (docs/examples/basic_example.py) | 00:01.469 | 0.0 MB | +-------------------------------------------------------------------------------------+-----------+--------+ | basic_widgets_demo (docs/examples/basic_widgets_demo.py) | 00:00.283 | 0.0 MB | +-------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/applications/callable/","title":"Callable functions demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/callable/#callable-functions-demo","title":"Callable functions demo","text":"

This example demonstrates handling callable functions with magicgui.

Out:

<FunctionGui example(func='f')>\n

from magicgui import magicgui\n\n\ndef f(x: int, y=\"a string\") -> str:\n    \"\"\"Example function F.\"\"\"\n    return f\"{y} {x}\"\n\n\ndef g(x: int = 6, y=\"another string\") -> str:\n    \"\"\"Example function G.\"\"\"\n    return f\"{y} asdfsdf {x}\"\n\n\n@magicgui(call_button=True, func={\"choices\": [\"f\", \"g\"]})\ndef example(func=\"f\"):\n    \"\"\"\u00cbxample function.\"\"\"\n    pass\n\n\ndef update(f: str):\n    \"\"\"Update function.\"\"\"\n    if len(example) > 2:\n        del example[1]\n    example.insert(1, magicgui(globals()[f]))\n\n\nexample.func.changed.connect(update)\nexample.show(run=True)\n

Total running time of the script: ( 0 minutes 0.196 seconds)

Download Python source code: callable.py

Download Jupyter notebook: callable.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/chaining/","title":"Chaining functions together","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/chaining/#chaining-functions-together","title":"Chaining functions together","text":"

This example demonstrates chaining multiple functions together.

Out:

calling func_a\ncalling func_b\ncalling func_c\n\n\n<Container (func_a: NoneType, func_b: NoneType, func_c: NoneType)>\n

from magicgui import magicgui, widgets\n\n\n@magicgui(auto_call=True)\ndef func_a(x: int = 64, y: int = 64):\n    \"\"\"Callable function A.\"\"\"\n    print(\"calling func_a\")\n    return x + y\n\n\n@magicgui(auto_call=True, input={\"visible\": False, \"label\": \" \", \"max\": 100000})\ndef func_b(input: int, mult=1.0):\n    \"\"\"Callable function B.\"\"\"\n    print(\"calling func_b\")\n    result = input * mult\n    # since these function defs live in globals(), you can update them directly\n    func_c.input.value = result\n    return result\n\n\n# alternatively, you can the `widget.called` signal to connect a callback function\n# where the result of the function being called is at `value`\n@func_a.called.connect\ndef _on_func_a(value: str):\n    func_b.input.value = value\n\n\n@magicgui(\n    auto_call=True,\n    input={\"visible\": False, \"max\": 100000},\n    result_widget=True,\n    labels=False,\n)\ndef func_c(input: int, format: str = \"({} + {}) * {} is {}\") -> str:\n    \"\"\"Callable function C.\"\"\"\n    print(\"calling func_c\\n\")\n    return format.format(func_a.x.value, func_a.y.value, func_b.mult.value, input)\n\n\ncontainer = widgets.Container(\n    widgets=[func_a, func_b, func_c], layout=\"vertical\", labels=False\n)\ncontainer.native.setMinimumWidth(500)\nfunc_a()\ncontainer.show(run=True)\n\n# notice which functions get called when you change each widget.\n

Total running time of the script: ( 0 minutes 0.110 seconds)

Download Python source code: chaining.py

Download Jupyter notebook: chaining.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/hotdog/","title":"Hotdog or not app","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/hotdog/#hotdog-or-not-app","title":"Hotdog or not app","text":"

Demo app to upload an image and classify if it's an hotdog or not.

import pathlib\nfrom enum import Enum\n\nfrom magicgui import magicgui\n\n\nclass HotdogOptions(Enum):\n    \"\"\"All hotdog possibilities.\"\"\"\n\n    Hotdog = 1\n    NotHotdog = 0\n\n\n@magicgui(main_window=True, layout=\"form\", call_button=\"Classify\", result_widget=True)\ndef is_hotdog(img: pathlib.Path) -> HotdogOptions:\n    \"\"\"Classify possible hotdog images.\n\n    Upload an image and check whether it's an hotdog. For example, this image\n    will be classified as one: <br><br>\n\n    <img src=\"resources/hotdog.jpg\">\n\n    Parameters\n    ----------\n    img : pathlib.Path\n        Path to a possible hotdog image\n\n    Returns\n    -------\n    HotdogOptions\n        True if image contains an hotdog in it\n    \"\"\"\n    if \"hotdog\" in img.stem:\n        return HotdogOptions.Hotdog\n    return HotdogOptions.NotHotdog\n\n\nif __name__ == \"__main__\":\n    is_hotdog.show(run=True)\n

Total running time of the script: ( 0 minutes 0.088 seconds)

Download Python source code: hotdog.py

Download Jupyter notebook: hotdog.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/mg_execution_times/","title":"Computation times","text":"

00:02.718 total execution time for generated_examples_applications files:

+-----------------------------------------------------------------------------------+-----------+--------+ | pint_quantity (docs/examples/applications/pint_quantity.py) | 00:02.223 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | callable (docs/examples/applications/callable.py) | 00:00.196 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | chaining (docs/examples/applications/chaining.py) | 00:00.110 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | snells_law (docs/examples/applications/snells_law.py) | 00:00.101 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | hotdog (docs/examples/applications/hotdog.py) | 00:00.088 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | values_dialog (docs/examples/applications/values_dialog.py) | 00:00.000 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/applications/pint_quantity/","title":"Quantities with pint","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/pint_quantity/#quantities-with-pint","title":"Quantities with pint","text":"

Pint is a Python package to define, operate and manipulate physical quantities: the product of a numerical value and a unit of measurement. It allows arithmetic operations between them and conversions from and to different units. https://pint.readthedocs.io/en/stable/

Out:

<FunctionGui widget(q=<Quantity(1, 'millisecond')>)>\n

from pint import Quantity\n\nfrom magicgui import magicgui\n\n\n@magicgui\ndef widget(q=Quantity(\"1 ms\")):\n    \"\"\"Widget allowing users to input quantity measurements.\"\"\"\n    print(q)\n\n\nwidget.show(run=True)\n

Total running time of the script: ( 0 minutes 2.223 seconds)

Download Python source code: pint_quantity.py

Download Jupyter notebook: pint_quantity.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/snells_law/","title":"Snell's law demonstration using magicgui","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/snells_law/#snells-law-demonstration-using-magicgui","title":"Snell's law demonstration using magicgui","text":"

Demo app for calculating angles of refraction according to Snell's law.

Out:

<FunctionGui snells_law(aoi=1.0, n1=<Medium.Glass: 1.52>, n2=<Medium.Water: 1.333>, degrees=True)>\n

import math\nfrom enum import Enum\n\nfrom magicgui import magicgui\n\n\nclass Medium(Enum):\n    \"\"\"Enum for various media and their refractive indices.\"\"\"\n\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(call_button=\"calculate\", result_widget=True)\ndef snells_law(aoi=1.0, n1=Medium.Glass, n2=Medium.Water, degrees=True):\n    \"\"\"Calculate the angle of refraction given two media and an AOI.\"\"\"\n    if degrees:\n        aoi = math.radians(aoi)\n    try:\n        n1 = n1.value\n        n2 = n2.value\n        result = math.asin(n1 * math.sin(aoi) / n2)\n        return round(math.degrees(result) if degrees else result, 2)\n    except ValueError:  # math domain error\n        return \"TIR!\"\n\n\nsnells_law.show(run=True)\n

Total running time of the script: ( 0 minutes 0.101 seconds)

Download Python source code: snells_law.py

Download Jupyter notebook: snells_law.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/values_dialog/","title":"Input values dialog","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/values_dialog/#input-values-dialog","title":"Input values dialog","text":"

A basic example of a user input dialog.

This will pause code execution until the user responds.

"},{"location":"generated_examples/applications/values_dialog/#_1","title":"Input values dialog","text":"
from magicgui.widgets import request_values\n\nvals = request_values(\n    age=int,\n    name={\"annotation\": str, \"label\": \"Enter your name:\"},\n    title=\"Hi, who are you?\",\n)\nprint(repr(vals))\n

Total running time of the script: ( 0 minutes 0.000 seconds)

Download Python source code: values_dialog.py

Download Jupyter notebook: values_dialog.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/change_label/","title":"Custom text labels for widgets","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/change_label/#custom-text-labels-for-widgets","title":"Custom text labels for widgets","text":"

An example showing how to create custom text labels for your widgets.

Out:

<FunctionGui example(x=1, y='hi')>\n

from magicgui import magicgui\n\n\n# use a different label than the default (the parameter name) in the UI\n@magicgui(x={\"label\": \"widget to set x\"})\ndef example(x=1, y=\"hi\"):\n    \"\"\"Example function.\"\"\"\n    return x, y\n\n\nexample.changed.connect(print)\nexample.show(run=True)\n

Total running time of the script: ( 0 minutes 0.082 seconds)

Download Python source code: change_label.py

Download Jupyter notebook: change_label.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/choices/","title":"Dropdown selection widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/choices/#dropdown-selection-widget","title":"Dropdown selection widget","text":"

Choices for dropdowns can be provided in a few different ways.

Out:

<Container (as_list: NoneType, as_enum: NoneType, as_2tuple: NoneType, as_function: NoneType)>\n

from enum import Enum\n\nfrom magicgui import magicgui, widgets\n\n\nclass Medium(Enum):\n    \"\"\"Enum for various media and their refractive indices.\"\"\"\n\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(ri={\"choices\": [\"Oil\", \"Water\", \"Air\"]}, auto_call=True)\ndef as_list(ri=\"Water\"):\n    \"\"\"Function decorated with magicgui list of choices.\"\"\"\n    print(\"refractive index is\", Medium[ri].value)\n\n\n@magicgui(auto_call=True)\ndef as_enum(ri: Medium = Medium.Water):\n    \"\"\"Function decorated with magicgui and enumeration.\"\"\"\n    print(\"refractive index is\", ri.value)\n\n\n@magicgui(\n    ri={\"choices\": [(\"Oil\", 1.515), (\"Water\", 1.33), (\"Air\", 1.0)]}, auto_call=True\n)\ndef as_2tuple(ri=1.33):\n    \"\"\"Function decorated with magicgui tuple of choices.\"\"\"\n    print(\"refractive index is\", ri)\n\n\ndef get_choices(gui):\n    \"\"\"Function returning tuple of material and refractive index value.\"\"\"\n    return [(\"Oil\", 1.515), (\"Water\", 1.33), (\"Air\", 1.0)]\n\n\n@magicgui(ri={\"choices\": get_choices}, auto_call=True)\ndef as_function(ri: float):\n    \"\"\"Function to calculate refractive index.\"\"\"\n    print(\"refractive index is\", ri)\n\n\ncontainer = widgets.Container(\n    widgets=[as_list, as_enum, as_2tuple, as_function], layout=\"vertical\"\n)\ncontainer.show(run=True)\n

Total running time of the script: ( 0 minutes 0.104 seconds)

Download Python source code: choices.py

Download Jupyter notebook: choices.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/file_dialog/","title":"File dialog widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/file_dialog/#file-dialog-widget","title":"File dialog widget","text":"

A file dialog widget example.

* ![file dialog](../images/mkd_glr_file_dialog_001.png){: .mkd-glr-multi-img srcset=\"../images/mkd_glr_file_dialog_001.png\"}\n\n* ![file dialog](../images/mkd_glr_file_dialog_002.png){: .mkd-glr-multi-img srcset=\"../images/mkd_glr_file_dialog_002.png\"}\n\n* ![file dialog](../images/mkd_glr_file_dialog_003.png){: .mkd-glr-multi-img srcset=\"../images/mkd_glr_file_dialog_003.png\"}\n
from pathlib import Path\nfrom typing import Sequence\n\nfrom magicgui import magicgui, use_app\n\n\n@magicgui(filename={\"mode\": \"r\"})\ndef filepicker(filename=Path(\"~\")):\n    \"\"\"Take a filename and do something with it.\"\"\"\n    print(\"The filename is:\", filename)\n    return filename\n\n\n# Sequence of paths\n# We change the label using \"label\" for added clarity\n# the filter argument restricts file types\n@magicgui(filenames={\"label\": \"Choose Tiff files:\", \"filter\": \"*.tif\"})\ndef filespicker(filenames: Sequence[Path]):\n    \"\"\"Take a filename and do something with it.\"\"\"\n    print(\"The filenames are:\", filenames)\n    return filenames\n\n\n# Select a directory, instead of file(s)\n@magicgui(directory={\"mode\": \"d\", \"label\": \"Choose a directory\"})\ndef directorypicker(directory=Path(\"~\")):\n    \"\"\"Take a directory name and do something with it.\"\"\"\n    print(\"The directory name is:\", directory)\n    return directory\n\n\nfilepicker.show()\nfilespicker.show()\ndirectorypicker.show()\nfilepicker.filename.changed.connect(print)\nfilespicker.filenames.changed.connect(print)\ndirectorypicker.directory.changed.connect(print)\n\nuse_app().run()\n

Total running time of the script: ( 0 minutes 0.163 seconds)

Download Python source code: file_dialog.py

Download Jupyter notebook: file_dialog.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/image/","title":"Image widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/image/#image-widget","title":"Image widget","text":"

Example of creating an Image Widget from a file.

(This requires pillow, or that magicgui was installed as magicgui[image])

Out:

Image(200x232x3, name='')\n

from magicgui.widgets import Image\n\nimage = Image(value=\"../../images/_test.jpg\")\nimage.scale_widget_to_image_size()\nimage.show(run=True)\n

Total running time of the script: ( 0 minutes 0.056 seconds)

Download Python source code: image.py

Download Jupyter notebook: image.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/log_slider/","title":"Log slider widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/log_slider/#log-slider-widget","title":"Log slider widget","text":"

A logarithmic scale range slider widget.

Out:

<FunctionGui slider(input=1.0)>\n

from magicgui import magicgui\n\n\n@magicgui(\n    auto_call=True,\n    result_widget=True,\n    input={\"widget_type\": \"LogSlider\", \"max\": 10000, \"min\": 1, \"tracking\": False},\n)\ndef slider(input=1):\n    \"\"\"Logarithmic scale slider.\"\"\"\n    return round(input, 4)\n\n\nslider.show(run=True)\n

Total running time of the script: ( 0 minutes 0.085 seconds)

Download Python source code: log_slider.py

Download Jupyter notebook: log_slider.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/login/","title":"Password login","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/login/#password-login","title":"Password login","text":"

A password login field widget.

Out:

<FunctionGui login(username: str = '', password: str = '', password2: str = '')>\n

from magicgui import magicgui\n\n\n# note that \"password\" is a special keyword argument\n# it will create a password field in the gui by default\n# (unless you override \"widget_type\")\n# whereas \"password2\" will be a normal text field\n# (unless you override \"widget_type\")\n@magicgui(password2={\"widget_type\": \"Password\"})\ndef login(username: str, password: str, password2: str):\n    \"\"\"User login credentials.\"\"\"\n    ...\n\n\nlogin.show(run=True)\n

Total running time of the script: ( 0 minutes 0.083 seconds)

Download Python source code: login.py

Download Jupyter notebook: login.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/mg_execution_times/","title":"Computation times","text":"

00:00.976 total execution time for generated_examples_demo_widgets files:

+--------------------------------------------------------------------------------+-----------+--------+ | file_dialog (docs/examples/demo_widgets/file_dialog.py) | 00:00.163 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | range_slider (docs/examples/demo_widgets/range_slider.py) | 00:00.149 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | choices (docs/examples/demo_widgets/choices.py) | 00:00.104 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | table (docs/examples/demo_widgets/table.py) | 00:00.093 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | selection (docs/examples/demo_widgets/selection.py) | 00:00.089 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | log_slider (docs/examples/demo_widgets/log_slider.py) | 00:00.085 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | login (docs/examples/demo_widgets/login.py) | 00:00.083 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | change_label (docs/examples/demo_widgets/change_label.py) | 00:00.082 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | optional (docs/examples/demo_widgets/optional.py) | 00:00.072 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | image (docs/examples/demo_widgets/image.py) | 00:00.056 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/demo_widgets/optional/","title":"Optional user choice","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/optional/#optional-user-choice","title":"Optional user choice","text":"

Optional user input using a dropdown selection widget.

Out:

<FunctionGui f(path: str = None)>\n

from typing import Optional\n\nfrom magicgui import magicgui\n\n\n# Using optional will add a '----' to the combobox, which returns \"None\"\n@magicgui(path={\"choices\": [\"a\", \"b\"]})\ndef f(path: Optional[str] = None):\n    \"\"\"\u00d6ptional user input function.\"\"\"\n    print(path, type(path))\n\n\nf.show(run=True)\n

Total running time of the script: ( 0 minutes 0.072 seconds)

Download Python source code: optional.py

Download Jupyter notebook: optional.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/range_slider/","title":"Range slider widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/range_slider/#range-slider-widget","title":"Range slider widget","text":"

A double ended range slider widget.

Out:

<FunctionGui func(range_value: Tuple[int, int] = (20, 380))>\n

from typing import Tuple\n\nfrom magicgui import magicgui\n\n\n@magicgui(auto_call=True, range_value={\"widget_type\": \"RangeSlider\", \"max\": 500})\ndef func(range_value: Tuple[int, int] = (20, 380)):\n    \"\"\"Double ended range slider.\"\"\"\n    print(range_value)\n\n\nfunc.show(run=True)\n

Total running time of the script: ( 0 minutes 0.149 seconds)

Download Python source code: range_slider.py

Download Jupyter notebook: range_slider.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/selection/","title":"Multiple selection widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/selection/#multiple-selection-widget","title":"Multiple selection widget","text":"

A selection widget allowing multiple selections by the user.

Out:

<FunctionGui my_widget(pick_some=['first'])>\n

from magicgui import magicgui\n\n\n@magicgui(\n    pick_some={\n        \"choices\": (\"first\", \"second\", \"third\", \"fourth\"),\n        \"allow_multiple\": True,\n    }\n)\ndef my_widget(pick_some=(\"first\")):\n    \"\"\"Dropdown selection function.\"\"\"\n    print(\"you selected\", pick_some)\n\n\nmy_widget.show(run=True)\n

Total running time of the script: ( 0 minutes 0.089 seconds)

Download Python source code: selection.py

Download Jupyter notebook: selection.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/table/","title":"Table widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/table/#table-widget","title":"Table widget","text":"

Demonstrating a few ways to input tables.

Out:

Table(shape=(6, 3) at 0x13564cc90)\n

import numpy as np\n\nfrom magicgui.widgets import Table\n\n# all of these are valid data types\ndict_of_lists = {\"col_1\": [1, 4], \"col_2\": [2, 5], \"col_3\": [3, 6]}\n# column-dict-of-row-dicts\ndict_of_dict = {\n    \"col_1\": {\"r1\": 1, \"r2\": 4},\n    \"col_2\": {\"r1\": 2, \"r2\": 5},\n    \"col_3\": {\"r1\": 3, \"r2\": 6},\n}\n# list-of-lists\nlist_of_list = [[1, 2, 3], [4, 5, 6]]\n# Records: List-of-column-dict\nlist_of_records = [\n    {\"col_1\": 1, \"col_2\": 2, \"col_3\": 3},\n    {\"col_1\": 4, \"col_2\": 5, \"col_3\": 6},\n]\n\n# 3-tuple of data, index, column\ndata_index_column_tuple = (([[1, 2, 3], [4, 5, 6]], (\"r1\", \"r2\"), (\"c1\", \"c2\", \"c3\")),)\n# split-dict\nsplit_dict = {\n    \"data\": [[1, 2, 3], [4, 5, 6]],\n    \"index\": (\"r1\", \"r2\"),\n    \"columns\": (\"c1\", \"c2\", \"c3\"),\n}\n\ntable = Table(value=dict_of_lists)\n\n# it behaves like a dict:\ntable[\"new_col\"] = [5, 5]\nassert table.pop(\"new_col\") == [5, 5]\n# keys and items have both regular (column) and \"row\" modes\ncol_item_view = table.items()  # iterate col_header/column\nrow_item_view = table.items(\"row\")  # iterate row_header/row\n\n# we can just call dict() to get back our dict of lists\nassert dict(table) == dict_of_lists\n# or use one of many other exports in `to_dict`\nassert table.to_dict(\"records\") == list_of_records\n\n# change headers\ntable.row_headers = (\"row1\", \"row2\")\ntable.column_headers = (\"a\", \"b\", \"c\")\n\n# setting value clears and resets the table:\ntable.value = np.arange(18).reshape(6, 3)\n# we can get/set/delete the 2D data table using numpy-style indexing:\n# get every other row\nassert table.data[::2] == [[0, 1, 2], [6, 7, 8], [12, 13, 14]]\n# set every other column in the 3rd row\ntable.data[2, ::2] = [99, 99]\n\n# export to numpy or pandas\n# table.data.to_numpy()\n# table.to_dataframe()\n\n# the table.changed event emits a dict of information on any cell change\n# e.g. {'data': 'sdfg', 'row': 1, 'column': 0, 'column_header': '1', 'row_header': '1'}\ntable.changed.connect(print)\ntable.show(run=True)\n

Total running time of the script: ( 0 minutes 0.093 seconds)

Download Python source code: table.py

Download Jupyter notebook: table.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/matplotlib/mg_execution_times/","title":"Computation times","text":"

00:00.814 total execution time for generated_examples_matplotlib files:

+------------------------------------------------------------------------+-----------+--------+ | waveform (docs/examples/matplotlib/waveform.py) | 00:00.522 | 0.0 MB | +------------------------------------------------------------------------+-----------+--------+ | mpl_figure (docs/examples/matplotlib/mpl_figure.py) | 00:00.292 | 0.0 MB | +------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/matplotlib/mpl_figure/","title":"matplotlib figure example","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/matplotlib/mpl_figure/#matplotlib-figure-example","title":"matplotlib figure example","text":"

Basic example of adding a generic QWidget to a container.

Main lesson: add your QWidget to container.native.layout() as shown on line 30

Out:

<FunctionGui f(position: int = 0)>\n

import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\n\nfrom magicgui import magicgui\n\nx = np.linspace(0, 5, 256)\ny = np.linspace(0, 5, 256)[:, np.newaxis]\ndata = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)\n\nmpl_fig = plt.figure()\nax = mpl_fig.add_subplot(111)\n(line,) = ax.plot(data[123])  # linescan through the middle of the image\n\n\n@magicgui(position={\"widget_type\": \"Slider\", \"max\": 255}, auto_call=True)\ndef f(position: int):\n    \"\"\"Function demonstrating magicgui combined with matplotlib.\"\"\"\n    line.set_ydata(data[position])\n    line.figure.canvas.draw()\n\n\n# rather than using the Container.append (`f.append`) ...\n# grab the native layout and add the QWidget to it\nf.native.layout().addWidget(FigureCanvas(mpl_fig))\n\nf.show(run=True)\n

Total running time of the script: ( 0 minutes 0.292 seconds)

Download Python source code: mpl_figure.py

Download Jupyter notebook: mpl_figure.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/matplotlib/waveform/","title":"Waveforms example","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/matplotlib/waveform/#waveforms-example","title":"Waveforms example","text":"

Simple waveform generator widget, with plotting.

Out:

<Container (signal_widget: NoneType, sine: NoneType)>\n

from dataclasses import dataclass, field\nfrom enum import Enum\nfrom functools import partial\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom scipy import signal\nfrom typing_extensions import Annotated\n\nfrom magicgui import magicgui, register_type, widgets\n\nregister_type(float, widget_type=\"FloatSlider\")\nregister_type(int, widget_type=\"Slider\")\n\nFreq = Annotated[float, {\"min\": 0.001, \"max\": 30.0}]\nPhase = Annotated[float, {\"min\": 0.0, \"max\": 360.0}]\nDuty = Annotated[float, {\"min\": 0.0, \"max\": 1.0}]\nTime = Annotated[float, {\"min\": 0.01, \"max\": 100.0}]\n\n\n@dataclass\nclass Signal:\n    \"\"\"Constructs a 1D signal.\n\n    As is, this class is not very useful, but one could add callbacks\n    or more functionality here\n\n    Parameters\n    ----------\n    func : callable\n        func must take a 'time' array as sole argument and return a 1D array with the\n        same size as the input\n    duration : float\n        the maximum of the input time array\n    size : int\n        the number of samples in the time array\n\n    \"\"\"\n\n    func: callable\n    duration: Time = 1.0\n    size: int = 500\n    time: np.ndarray = field(init=False)\n    data: np.ndarray = field(init=False)\n\n    def __post_init__(self):\n        \"\"\"Evaluate the function at instantiation time.\"\"\"\n        self.time = np.linspace(0, self.duration, self.size)\n        self.data = self.func(self.time)\n\n    def plot(self, ax=None, **kwargs):\n        \"\"\"Plots the data.\n\n        Parameters\n        ----------\n        ax: matplotlib.axes.Axes instance, default None\n           if provided the plot is done on this axes instance.\n           If None a new ax is created\n        **kwargs: Keyword arguments that are passed on to\n            the matplotib ax.plot method\n\n        Returns\n        -------\n        fig: a matplotlib.figure.Figure instance\n        ax: matplotlib.axes.Axes instance\n        \"\"\"\n        if ax is None:\n            fig, ax = plt.subplots()\n        else:\n            fig = ax.get_figure()\n        ax.plot(self.time, self.data, **kwargs)\n        return fig, ax\n\n\ndef sine(\n    duration: Time = 10.0, size: int = 500, freq: Freq = 0.5, phase: Phase = 0.0\n) -> Signal:\n    \"\"\"Returns a 1D sine wave.\n\n    Parameters\n    ----------\n    duration: float\n       the duration of the signal in seconds\n    size: int\n        the number of samples in the signal time array\n    freq: float\n       the frequency of the signal in Hz\n    phase: Phase\n       the phase of the signal (in degrees)\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=lambda t: np.sin(t * (2 * np.pi * freq) + phase * np.pi / 180),\n    )\n    return sig\n\n\ndef chirp(\n    duration: Time = 10.0,\n    size: int = 500,\n    f0: float = 1.0,\n    t1: Time = 5.0,\n    f1: float = 2.0,\n    phase: Phase = 0.0,\n) -> Signal:\n    \"\"\"Frequency-swept cosine generator.\n\n    See scipy.signal.chirp\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=partial(signal.chirp, f0=f0, t1=t1, f1=f1, phi=phase),\n    )\n    return sig\n\n\ndef sawtooth(\n    duration: Time = 10.0,\n    size: int = 500,\n    freq: Freq = 1.0,\n    width: Duty = 1.0,\n    phase: Phase = 0.0,\n) -> Signal:\n    \"\"\"Return a periodic sawtooth or triangle waveform.\n\n    See scipy.signal.sawtooth\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=lambda t: signal.sawtooth(\n            2 * np.pi * freq * t + phase * np.pi / 180, width=width\n        ),\n    )\n    return sig\n\n\ndef square(\n    duration: Time = 10.0, size: int = 500, freq: Freq = 1.0, duty: Duty = 0.5\n) -> Signal:\n    \"\"\"Return a periodic sawtooth or triangle waveform.\n\n    See scipy.signal.square\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=lambda t: signal.square(2 * np.pi * freq * t, duty=duty),\n    )\n    return sig\n\n\ndef on_off(\n    duration: Time = 10.0, size: int = 500, t_on: Time = 0.01, t_off: Time = 0.01\n) -> Signal:\n    \"\"\"On/Off signal function.\"\"\"\n    data = np.ones(size)\n    data[: int(size * t_on / duration)] = -1\n    if t_off > 0:\n        data[int(size * t_off / duration) :] = -1\n    sig = Signal(duration=duration, size=size, func=lambda t: data)\n    return sig\n\n\nWAVEFORMS = {\n    \"sine\": sine,\n    \"chirp\": chirp,\n    \"sawtooth\": sawtooth,\n    \"square\": square,\n    \"on_off\": on_off,\n}\n\n\nclass Select(Enum):\n    \"\"\"Enumeration to select signal type.\"\"\"\n\n    OnOff = \"on_off\"\n    Sine = \"sine\"\n    Chirp = \"chirp\"\n    Sawtooth = \"sawtooth\"\n    Square = \"square\"\n\n\nclass WaveForm(widgets.Container):\n    \"\"\"Simple waveform generator widget, with plotting.\"\"\"\n\n    def __init__(self):\n        \"\"\"Creates the widget.\"\"\"\n        super().__init__()\n        self.fig, self.ax = plt.subplots()\n        self.native.layout().addWidget(FigureCanvas(self.fig))\n        self.waveform = sine\n        self.controls = None\n        self.append(self.signal_widget)\n        self.update_controls()\n        self.update_graph(sine())\n\n    @magicgui(auto_call=True)\n    def signal_widget(self, select: Select = Select.Sine) -> widgets.Container:\n        \"\"\"Waveform selection, from the WAVEFORMS dict.\"\"\"\n        self.waveform = WAVEFORMS[select.value]\n        self.update_controls()\n        self.update_graph(self.waveform())\n\n    def update_controls(self):\n        \"\"\"Reset controls according to the new function.\"\"\"\n        if self.controls is not None:\n            self.remove(self.controls)\n        self.controls = magicgui(auto_call=True)(self.waveform)\n        self.append(self.controls)\n        self.controls.called.connect(self.update_graph)\n\n    def update_graph(self, sig: Signal):\n        \"\"\"Re-plot when a parameter changes.\n\n        Note\n        ----\n        For big data, this could be slow, maybe `auto_call` should\n        not be true in the method above...\n        \"\"\"\n        self.ax.cla()\n        sig.plot(ax=self.ax)\n        self.fig.canvas.draw()\n\n\nwaveform = WaveForm()\nwaveform.show(run=True)\n

Total running time of the script: ( 0 minutes 0.522 seconds)

Download Python source code: waveform.py

Download Jupyter notebook: waveform.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/mg_execution_times/","title":"Computation times","text":"

00:29.257 total execution time for generated_examples_napari files:

+--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_combine_qt (docs/examples/napari/napari_combine_qt.py) | 00:19.594 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_parameter_sweep (docs/examples/napari/napari_parameter_sweep.py) | 00:05.948 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_img_math (docs/examples/napari/napari_img_math.py) | 00:03.612 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_forward_refs (docs/examples/napari/napari_forward_refs.py) | 00:00.102 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/napari/napari_combine_qt/","title":"napari Qt demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_combine_qt/#napari-qt-demo","title":"napari Qt demo","text":"

Napari provides a few conveniences with magicgui, and one of the most commonly used is the layer combo box that gets created when a parameter is annotated as napari.layers.Layer.

The layer box will stay in sync with the viewer model, adding and removing layers as needed.

This example shows how to use just that widget in the context of a larger custom QWidget.

Out:

0.00s - Debugger warning: It seems that frozen modules are being used, which may\n0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off\n0.00s - to python to disable frozen modules.\n0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.\n

import napari\nfrom qtpy.QtWidgets import QVBoxLayout, QWidget\n\nfrom magicgui.widgets import create_widget\n\n\nclass CustomWidget(QWidget):\n    \"\"\"A custom widget class.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n        self.setLayout(QVBoxLayout())\n        # change annotation to napari.layers.Image (e.g) to restrict to just Images\n        self._layer_combo = create_widget(annotation=napari.layers.Layer)\n        # magicgui widgets hold the Qt widget at `widget.native`\n        self.layout().addWidget(self._layer_combo.native)\n\n\nviewer = napari.Viewer()\nviewer.add_points()\nviewer.add_points()\n\nmy_widget = CustomWidget()\nviewer.window.add_dock_widget(my_widget)\n\n# when my_widget is a magicgui.Widget, it will detect that it has been added\n# to a viewer, and automatically update the choices.  Otherwise, you need to\n# trigger this yourself:\nmy_widget._layer_combo.reset_choices()\nviewer.layers.events.inserted.connect(my_widget._layer_combo.reset_choices)\nviewer.layers.events.removed.connect(my_widget._layer_combo.reset_choices)\n\nnapari.run()\n

Total running time of the script: ( 0 minutes 19.594 seconds)

Download Python source code: napari_combine_qt.py

Download Jupyter notebook: napari_combine_qt.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/napari_forward_refs/","title":"napari forward reference demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_forward_refs/#napari-forward-reference-demo","title":"napari forward reference demo","text":"

Example of using a ForwardRef to avoid importing a module that provides a widget.

In this example, one might want to create a widget that takes as an argument a napari Image layer, and returns an Image. In order to avoid needing to import napari (and therefore depending directly on napari), it's possible to annotate those parameters with a string representation of the type (rather than the type itself). This is called a \"forward reference\": https://www.python.org/dev/peps/pep-0484/#forward-references

Out:

<FunctionGui subtract_background(data: napari.types.ImageData = None, background: int = 50) -> napari.types.ImageData>\n

# Note: if you'd like to avoid circular imports, or just want to avoid having your\n# linter yell at you for an undefined type annotation, you can place the import\n# inside of an `if typing.TYPE_CHECKING` conditional.  This is not evaluated at runtime,\n# only when something like mypy is doing type checking.\nfrom typing import TYPE_CHECKING\n\nfrom magicgui import magicgui\n\nif TYPE_CHECKING:\n    import napari\n\n\n@magicgui(call_button=\"execute\", background={\"max\": 200})\ndef subtract_background(\n    data: \"napari.types.ImageData\", background: int = 50\n) -> \"napari.types.ImageData\":\n    \"\"\"Subtract a constant from the data.\"\"\"\n    if data:\n        return data - background\n\n\nsubtract_background.show(run=True)\n# now, this example isn't all that interesting on its own (since there will be no Image\n# layer in the dropdown) ... but in another package, where you DO import napari,\n# you could add this widget to a napari viewer with\n# viewer.window.add_dock_widget(subtract_background)\n

Total running time of the script: ( 0 minutes 0.102 seconds)

Download Python source code: napari_forward_refs.py

Download Jupyter notebook: napari_forward_refs.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/napari_img_math/","title":"napari image arithmetic widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_img_math/#napari-image-arithmetic-widget","title":"napari image arithmetic widget","text":"

napari is a fast, interactive, multi-dimensional image viewer for python. It uses Qt for the GUI, so it's easy to extend napari with small, composable widgets created with magicgui. Here we're going to build this simple image arithmetic widget with a few additional lines of code.

For napari-specific magicgui documentation, see the napari docs

"},{"location":"generated_examples/napari/napari_img_math/#outline","title":"outline","text":"

This example demonstrates how to:

  1. Create a magicgui widget that can be used in another program (napari)

  2. Use an Enum to create a dropdown menu

  3. Connect some event listeners to create interactivity.

"},{"location":"generated_examples/napari/napari_img_math/#code","title":"code","text":"

Code follows, with explanation below... You can also get this example at github.

from enum import Enum\n\nimport napari\nimport numpy\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\nclass Operation(Enum):\n    # A set of valid arithmetic operations for image_arithmetic.\n    #\n    # To create nice dropdown menus with magicgui, it's best\n    # (but not required) to use Enums.  Here we make an Enum\n    # class for all of the image math operations we want to\n    # allow.\n    add = numpy.add\n    subtract = numpy.subtract\n    multiply = numpy.multiply\n    divide = numpy.divide\n\n\n# here's the magicgui!  We also use the additional\n# `call_button` option\n@magicgui(call_button=\"execute\")\ndef image_arithmetic(\n    layerA: ImageData, operation: Operation, layerB: ImageData\n) -> ImageData:\n    # Add, subtracts, multiplies, or divides to image layers.\n    return operation.value(layerA, layerB)\n\n# create a viewer and add a couple image layers\nviewer = napari.Viewer()\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 1\")\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 2\")\n\n# add our new magicgui widget to the viewer\nviewer.window.add_dock_widget(image_arithmetic)\n\n# keep the dropdown menus in the gui in sync with the layer model\nviewer.layers.events.inserted.connect(image_arithmetic.reset_choices)\nviewer.layers.events.removed.connect(image_arithmetic.reset_choices)\n\nnapari.run()\n
"},{"location":"generated_examples/napari/napari_img_math/#walkthrough","title":"walkthrough","text":"

We're going to go a little out of order so that the other code makes more sense. Let's start with the actual function we'd like to write to do some image arithmetic.

"},{"location":"generated_examples/napari/napari_img_math/#the-function","title":"the function","text":"

Our function takes two numpy arrays (in this case, from Image layers), and some mathematical operation (we'll restrict the options using an enum.Enum). When called, ourfunction calls the selected operation on the data.

def image_arithmetic(array1, operation, array2):\n    return operation.value(array1, array2)\n
"},{"location":"generated_examples/napari/napari_img_math/#type-annotations","title":"type annotations","text":"

magicgui works particularly well with type annotations, and allows third-party libraries to register widgets and behavior for handling their custom types (using magicgui.type_map.register_type). napari provides support for magicgui by registering a dropdown menu whenever a function parameter is annotated as one of the basic napari Layer types, or, in this case, ImageData indicates we just the data attribute of the layer. Furthermore, it recognizes when a function has a napari.layers.Layer or LayerData return type annotation, and will add the result to the viewer. So we gain a lot by annotating the above function with the appropriate napari types.

from napari.types import ImageData\n\ndef image_arithmetic(\n    layerA: ImageData, operation: Operation, layerB: ImageData\n) -> ImageData:\n    return operation.value(layerA, layerB)\n
"},{"location":"generated_examples/napari/napari_img_math/#the-magic-part","title":"the magic part","text":"

Finally, we decorate the function with @magicgui and tell it we'd like to have a call_button that we can click to execute the function.

@magicgui(call_button=\"execute\")\ndef image_arithmetic(layerA: ImageData, operation: Operation, layerB: ImageData):\n    return operation.value(layerA, layerB)\n

That's it! The image_arithmetic function is now a FunctionGui that can be shown, or incorporated into other GUIs (such as the napari GUI shown in this example)

!!! note While type hints aren't always required in magicgui, they are recommended ... and they are required for certain things, like the Operation(Enum) used here for the dropdown and the napari.types.ImageData annotations that napari has registered with magicgui.

"},{"location":"generated_examples/napari/napari_img_math/#create-dropdowns-with-enums","title":"create dropdowns with Enums","text":"

We'd like the user to be able to select the operation (add, subtract, multiply, divide) using a dropdown menu. enum.Enum offers a convenient way to restrict values to a strict set of options, while providing name: value pairs for each of the options. Here, the value for each choice is the actual function we would like to have called when that option is selected.

class Operation(enum.Enum):\n    add = numpy.add\n    subtract = numpy.subtract\n    multiply = numpy.multiply\n    divide = numpy.divide\n
"},{"location":"generated_examples/napari/napari_img_math/#add-it-to-napari","title":"add it to napari","text":"

When we decorated the image_arithmetic function above, it became a FunctionGui. Napari recognizes this type, so we can simply add it to the napari viewer as follows:

viewer.window.add_dock_widget(image_arithmetic)\n
"},{"location":"generated_examples/napari/napari_img_math/#connect-event-listeners-for-interactivity","title":"connect event listeners for interactivity","text":"

What fun is a GUI without some interactivity? Let's make stuff happen.

We connect the image_arithmetic.reset_choices function to the viewer.layers.events.inserted/removed event from napari, to make sure that the dropdown menus stay in sync if a layer gets added or removed from the napari window:

viewer.layers.events.inserted.connect(image_arithmetic.reset_choices)\nviewer.layers.events.removed.connect(image_arithmetic.reset_choices)\n

Tip

An additional offering from magicgui here is that the decorated function also acquires a new attribute \"called\" that can be connected to callback functions of your choice. Then, whenever the gui widget or the original function are called, the result will be passed to your callback function:

@image_arithmetic.called.connect\ndef print_mean(value):\n    # Callback function that accepts an event\n    # the value attribute has the result of calling the function\n    print(np.mean(value))\n
>>> image_arithmetic()\n1.0060037881040373\n
"},{"location":"generated_examples/napari/napari_img_math/#code_1","title":"Code","text":"

Here's the full code example again.

from enum import Enum\n\nimport napari\nimport numpy\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\nclass Operation(Enum):\n    # A set of valid arithmetic operations for image_arithmetic.\n    #\n    # To create nice dropdown menus with magicgui, it's best\n    # (but not required) to use Enums.  Here we make an Enum\n    # class for all of the image math operations we want to\n    # allow.\n    add = numpy.add\n    subtract = numpy.subtract\n    multiply = numpy.multiply\n    divide = numpy.divide\n\n\n# here's the magicgui!  We also use the additional\n# `call_button` option\n@magicgui(call_button=\"execute\")\ndef image_arithmetic(\n    layerA: ImageData, operation: Operation, layerB: ImageData\n) -> ImageData:\n    # Add, subtracts, multiplies, or divides to image layers.\n    return operation.value(layerA, layerB)\n\n\n# create a viewer and add a couple image layers\nviewer = napari.Viewer()\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 1\")\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 2\")\n\n# add our new magicgui widget to the viewer\nviewer.window.add_dock_widget(image_arithmetic)\n\n# keep the dropdown menus in the gui in sync with the layer model\nviewer.layers.events.inserted.connect(image_arithmetic.reset_choices)\nviewer.layers.events.removed.connect(image_arithmetic.reset_choices)\n\nnapari.run()\n

Total running time of the script: ( 0 minutes 3.612 seconds)

Download Python source code: napari_img_math.py

Download Jupyter notebook: napari_img_math.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/napari_parameter_sweep/","title":"napari parameter sweeps","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_parameter_sweep/#napari-parameter-sweeps","title":"napari parameter sweeps","text":"

napari is a fast, interactive, multi-dimensional image viewer for python. It uses Qt for the GUI, so it's easy to extend napari with small, composable widgets created with magicgui. Here, we demonstrate how to build a interactive widget that lets you immediately see the effect of changing one of the parameters of your function.

For napari-specific magicgui documentation, see the napari docs

See also: Some of this tutorial overlaps with topics covered in the napari image arithmetic example.

"},{"location":"generated_examples/napari/napari_parameter_sweep/#outline","title":"outline","text":"

This example demonstrates how to:

  1. Create a magicgui widget that can be used in another program (napari)

  2. Automatically call our function when a parameter changes

  3. Provide magicgui with a custom widget for a specific argument

  4. Use the choices option to create a dropdown

  5. Connect some event listeners to create interactivity.

"},{"location":"generated_examples/napari/napari_parameter_sweep/#code","title":"code","text":"

Code follows, with explanation below... You can also get this example at github.

import napari\nimport skimage.data\nimport skimage.filters\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\n# turn the gaussian blur function into a magicgui\n# - 'auto_call' tells magicgui to call the function when a parameter changes\n# - we use 'widget_type' to override the default \"float\" widget on sigma,\n#   and provide a maximum valid value.\n# - we contstrain the possible choices for 'mode'\n@magicgui(\n    auto_call=True,\n    sigma={\"widget_type\": \"FloatSlider\", \"max\": 6},\n    mode={\"choices\": [\"reflect\", \"constant\", \"nearest\", \"mirror\", \"wrap\"]},\n    layout=\"horizontal\",\n)\ndef gaussian_blur(layer: ImageData, sigma: float = 1.0, mode=\"nearest\") -> ImageData:\n    # Apply a gaussian blur to 'layer'.\n    if layer is not None:\n        return skimage.filters.gaussian(layer, sigma=sigma, mode=mode)\n\n# create a viewer and add some images\nviewer = napari.Viewer()\nviewer.add_image(skimage.data.astronaut().mean(-1), name=\"astronaut\")\nviewer.add_image(skimage.data.grass().astype(\"float\"), name=\"grass\")\n\n# Add it to the napari viewer\nviewer.window.add_dock_widget(gaussian_blur)\n# update the layer dropdown menu when the layer list changes\nviewer.layers.events.changed.connect(gaussian_blur.reset_choices)\n\nnapari.run()\n
"},{"location":"generated_examples/napari/napari_parameter_sweep/#walkthrough","title":"walkthrough","text":"

We're going to go a little out of order so that the other code makes more sense. Let's start with the actual function we'd like to write to apply a gaussian filter to an image.

"},{"location":"generated_examples/napari/napari_parameter_sweep/#the-function","title":"the function","text":"

Our function is a very thin wrapper around skimage.filters.gaussian. It takes a napari Image layer, a sigma to control the blur radius, and a mode that determines how edges are handled.

def gaussian_blur(\n    layer: Image, sigma: float = 1, mode=\"nearest\"\n) -> Image:\n    return filters.gaussian(layer.data, sigma=sigma, mode=mode)\n

The reasons we are wrapping it here are:

  1. filters.gaussian accepts a numpy array, but we want to work with napari layers that store the data in a layer.data attribute. So we need an adapter.
  2. We'd like to add some type annotations to the signature that were not provided by filters.gaussian
"},{"location":"generated_examples/napari/napari_parameter_sweep/#type-annotations","title":"type annotations","text":"

As described in the image arithmetic example, we take advantage of napari's built in support for magicgui by annotating our function parameters and return value as napari Layer types. napari will then tell magicgui what to do with them, creating a dropdown with a list of current layers for our layer parameter, and automatically adding the result of our function to the viewer when called.

For documentation on napari types with magicgui, see the napari docs

"},{"location":"generated_examples/napari/napari_parameter_sweep/#the-magic-part","title":"the magic part","text":"

Finally, we decorate the function with @magicgui and provide some options.

@magicgui(\n    auto_call=True,\n    sigma={\"widget_type\": \"FloatSlider\", \"max\": 6},\n    mode={\"choices\": [\"reflect\", \"constant\", \"nearest\", \"mirror\", \"wrap\"]},\n)\ndef gaussian_blur(\n  layer: ImageData, sigma: float = 1.0, mode=\"nearest\"\n) -> ImageData:\n    # Apply a gaussian blur to ``layer``.\n    if layer is not None:\n        return skimage.filters.gaussian(layer, sigma=sigma, mode=mode)\n
"},{"location":"generated_examples/napari/napari_parameter_sweep/#connecting-events","title":"connecting events","text":"

As described in the Events documentation, we can also connect any callback to the gaussian_blur.called signal that will receive the result of our decorated function anytime it is called.

def do_something_with_result(result):\n    ...\n\ngaussian_blur.called.connect(do_something_with_result)\n
"},{"location":"generated_examples/napari/napari_parameter_sweep/#code_1","title":"Code","text":"

Here's the full code example again.

import napari\nimport skimage.data\nimport skimage.filters\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\n# turn the gaussian blur function into a magicgui\n# - 'auto_call' tells magicgui to call the function when a parameter changes\n# - we use 'widget_type' to override the default \"float\" widget on sigma,\n#   and provide a maximum valid value.\n# - we contstrain the possible choices for 'mode'\n@magicgui(\n    auto_call=True,\n    sigma={\"widget_type\": \"FloatSlider\", \"max\": 6},\n    mode={\"choices\": [\"reflect\", \"constant\", \"nearest\", \"mirror\", \"wrap\"]},\n    layout=\"horizontal\",\n)\ndef gaussian_blur(layer: ImageData, sigma: float = 1.0, mode=\"nearest\") -> ImageData:\n    # Apply a gaussian blur to 'layer'.\n    if layer is not None:\n        return skimage.filters.gaussian(layer, sigma=sigma, mode=mode)\n\n\n# create a viewer and add some images\nviewer = napari.Viewer()\nviewer.add_image(skimage.data.astronaut().mean(-1), name=\"astronaut\")\nviewer.add_image(skimage.data.grass().astype(\"float\"), name=\"grass\")\n\n# Add it to the napari viewer\nviewer.window.add_dock_widget(gaussian_blur)\n# update the layer dropdown menu when the layer list changes\nviewer.layers.events.changed.connect(gaussian_blur.reset_choices)\n\nnapari.run()\n

Total running time of the script: ( 0 minutes 5.948 seconds)

Download Python source code: napari_parameter_sweep.py

Download Jupyter notebook: napari_parameter_sweep.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/notebooks/magicgui_jupyter/","title":"Jupyter notebooks and magicgui","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/notebooks/magicgui_jupyter/#jupyter-notebooks-and-magicgui","title":"Jupyter notebooks and magicgui","text":"

This example shows magicgui widgets embedded in a jupyter notebook.

The key function here is use_app(\"ipynb\").

You can also get this example at github.

import math\nfrom enum import Enum\n\nfrom magicgui import magicgui, use_app\nuse_app(\"ipynb\")\n\nclass Medium(Enum):\n    # Various media and their refractive indices.\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(\n    call_button=\"calculate\", result_widget=True, layout='vertical', auto_call=True\n)\ndef snells_law(aoi=1.0, n1=Medium.Glass, n2=Medium.Water, degrees=True):\n    # Calculate the angle of refraction given two media and an angle of incidence.\n    if degrees:\n        aoi = math.radians(aoi)\n    try:\n        n1 = n1.value\n        n2 = n2.value\n        result = math.asin(n1 * math.sin(aoi) / n2)\n        return round(math.degrees(result) if degrees else result, 2)\n    except ValueError:  # math domain error\n        return \"TIR!\"\n\n\nsnells_law\n

Total running time of the script: ( 0 minutes 0.000 seconds)

Download Python source code: magicgui_jupyter.py

Download Jupyter notebook: magicgui_jupyter.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/notebooks/mg_execution_times/","title":"Computation times","text":"

00:00.000 total execution time for generated_examples_notebooks files:

+-----------------------------------------------------------------------------------------+-----------+--------+ | magicgui_jupyter (docs/examples/notebooks/magicgui_jupyter.py) | 00:00.000 | 0.0 MB | +-----------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/progress_bars/mg_execution_times/","title":"Computation times","text":"

00:00.302 total execution time for generated_examples_progress_bars files:

+---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress_nested (docs/examples/progress_bars/progress_nested.py) | 00:00.097 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress_manual (docs/examples/progress_bars/progress_manual.py) | 00:00.075 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress (docs/examples/progress_bars/progress.py) | 00:00.068 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress_indeterminate (docs/examples/progress_bars/progress_indeterminate.py) | 00:00.062 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/progress_bars/progress/","title":"Simple progress bar","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress/#simple-progress-bar","title":"Simple progress bar","text":"

A simple progress bar demo with magicgui.

Out:

<FunctionGui long_running(steps=10, delay=0.1)>\n

from time import sleep\n\nfrom magicgui import magicgui\nfrom magicgui.tqdm import trange\n\n# if magicui.tqdm.tqdm or trange are used outside of a @magicgui function, (such as in\n# interactive use in IPython), then they fall back to the standard terminal output\n\n\n# If use inside of a magicgui-decorated function\n# a progress bar widget will be added to the magicgui container\n@magicgui(call_button=True, layout=\"horizontal\")\ndef long_running(steps=10, delay=0.1):\n    \"\"\"Long running computation with range iterator.\"\"\"\n    # trange(steps) is a shortcut for `tqdm(range(steps))`\n    for _i in trange(steps):\n        sleep(delay)\n\n\nlong_running.show(run=True)\n

Total running time of the script: ( 0 minutes 0.068 seconds)

Download Python source code: progress.py

Download Jupyter notebook: progress.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/progress_bars/progress_indeterminate/","title":"Indeterminate progress bar","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress_indeterminate/#indeterminate-progress-bar","title":"Indeterminate progress bar","text":"

Example of an indeterminate progress bar for a long running computation of unknown time.

Out:

<FunctionGui long_running(sleep_time=5)>\n

import time\n\nfrom superqt.utils import thread_worker\n\nfrom magicgui import magicgui\nfrom magicgui.tqdm import tqdm\n\n\n@magicgui(call_button=True, layout=\"horizontal\")\ndef long_running(sleep_time=5):\n    \"\"\"Long running computation with an indeterminate progress bar.\"\"\"\n    # Here tqdm is not provided an iterable argument, or the 'total' kwarg\n    # so it cannot calculate the expected number of iterations\n    # which means it will create an indeterminate progress bar\n    with tqdm() as pbar:\n        # It is best practice to use a separate thread for long running computations\n        # This makes the function non-blocking, you can still interact with the widget\n        @thread_worker(connect={\"finished\": lambda: pbar.progressbar.hide()})\n        def sleep(secs):\n            time.sleep(secs)\n\n        sleep(sleep_time)\n\n\nlong_running.show(run=True)\n

Total running time of the script: ( 0 minutes 0.062 seconds)

Download Python source code: progress_indeterminate.py

Download Jupyter notebook: progress_indeterminate.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/progress_bars/progress_manual/","title":"Manual progress bar","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress_manual/#manual-progress-bar","title":"Manual progress bar","text":"

Example of a progress bar being updated manually.

Out:

<FunctionGui manual(pbar: magicgui.widgets.ProgressBar = ProgressBar(value=<function match_type.<locals>.<lambda> at 0x13e3f9940>, annotation=<class 'magicgui.widgets.ProgressBar'>, name='pbar'), increment: bool = 1)>\n

from magicgui import magicgui\nfrom magicgui.widgets import ProgressBar\n\n\n@magicgui(call_button=\"tick\", pbar={\"min\": 0, \"step\": 2, \"max\": 20, \"value\": 0})\ndef manual(pbar: ProgressBar, increment: bool = True):\n    \"\"\"Example of manual progress bar control.\"\"\"\n    if increment:\n        pbar.increment()\n    else:\n        pbar.decrement()\n\n\nmanual.show(run=True)\n

Total running time of the script: ( 0 minutes 0.075 seconds)

Download Python source code: progress_manual.py

Download Jupyter notebook: progress_manual.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/progress_bars/progress_nested/","title":"Nested progress bars","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress_nested/#nested-progress-bars","title":"Nested progress bars","text":"

Example using nested progress bars in magicgui.

Out:

<FunctionGui long_function(steps=10, repeats=4, choices='ABCDEFGHIJKLMNOP12345679', char='', delay=0.05)>\n

import random\nfrom time import sleep\n\nfrom magicgui import magicgui\nfrom magicgui.tqdm import tqdm, trange\n\n# if magicui.tqdm.tqdm or trange are used outside of a @magicgui function, (such as in\n# interactive use in IPython), then they fall back to the standard terminal output\n\n\n# If use inside of a magicgui-decorated function\n# a progress bar widget will be added to the magicgui container\n@magicgui(call_button=True, layout=\"vertical\")\ndef long_function(\n    steps=10, repeats=4, choices=\"ABCDEFGHIJKLMNOP12345679\", char=\"\", delay=0.05\n):\n    \"\"\"Long running computation with nested iterators.\"\"\"\n    # trange and tqdm accept all the kwargs from tqdm itself, as well as any\n    # valid kwargs for magicgui.widgets.ProgressBar, (such as \"label\")\n    for _r in trange(repeats, label=\"repeats\"):\n        letters = [random.choice(choices) for _ in range(steps)]\n        # `tqdm`, like `tqdm`, accepts any iterable\n        # this progress bar is nested and will be run & reset multiple times\n        for letter in tqdm(letters, label=\"steps\"):\n            long_function.char.value = letter\n            sleep(delay)\n\n\nlong_function.show(run=True)\n

Total running time of the script: ( 0 minutes 0.097 seconds)

Download Python source code: progress_nested.py

Download Jupyter notebook: progress_nested.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/under_the_hood/class_method/","title":"Deocrate class methods with magicgui","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/under_the_hood/class_method/#deocrate-class-methods-with-magicgui","title":"Deocrate class methods with magicgui","text":"

Demonstrates decorating a class method with magicgui.

Once the class is instantiated, instance.method_name will return a FunctionGui in which the instance will always be provided as the first argument (i.e. \"self\") when the FunctionGui or method is called.

Out:

instance: a, counter: 0.0, sigma: 0.0\ninstance: b, counter: 0.0, sigma: 0.0\n

from magicgui import event_loop, magicgui\nfrom magicgui.widgets import Container\n\n\nclass MyObject:\n    \"\"\"Example object class.\"\"\"\n\n    def __init__(self, name):\n        self.name = name\n        self.counter = 0.0\n\n    @magicgui(auto_call=True)\n    def method(self, sigma: float = 0):\n        \"\"\"Example class method.\"\"\"\n        print(f\"instance: {self.name}, counter: {self.counter}, sigma: {sigma}\")\n        self.counter = self.counter + sigma\n        return self.name\n\n\nwith event_loop():\n    a = MyObject(\"a\")\n    b = MyObject(\"b\")\n    container = Container(widgets=[a.method, b.method])\n    container.show()\n    assert a.method() == \"a\"\n    assert b.method() == \"b\"\n

Total running time of the script: ( 0 minutes 0.050 seconds)

Download Python source code: class_method.py

Download Jupyter notebook: class_method.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/under_the_hood/mg_execution_times/","title":"Computation times","text":"

00:00.111 total execution time for generated_examples_under_the_hood files:

+----------------------------------------------------------------------------------------+-----------+--------+ | self_reference (docs/examples/under_the_hood/self_reference.py) | 00:00.061 | 0.0 MB | +----------------------------------------------------------------------------------------+-----------+--------+ | class_method (docs/examples/under_the_hood/class_method.py) | 00:00.050 | 0.0 MB | +----------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/under_the_hood/self_reference/","title":"Self reference magicgui widgets","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/under_the_hood/self_reference/#self-reference-magicgui-widgets","title":"Self reference magicgui widgets","text":"

Widgets created with magicgui can reference themselves, and use the widget API.

Out:

<FunctionGui function(width=400, x: int = 50)>\n

from magicgui import magicgui\n\n\n@magicgui(auto_call=True, width={\"max\": 800, \"min\": 100}, x={\"widget_type\": \"Slider\"})\ndef function(width=400, x: int = 50):\n    \"\"\"Example function.\"\"\"\n    # the widget can reference itself, and use the widget API\n    function.x.width = width\n\n\nfunction.show(run=True)\n

Total running time of the script: ( 0 minutes 0.061 seconds)

Download Python source code: self_reference.py

Download Jupyter notebook: self_reference.ipynb

Gallery generated by mkdocs-gallery

"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"magicgui \ud83e\uddd9","text":"

magicgui is a python library for building graphical user interfaces (GUIs).

It aims to speed up data workflows by providing a simple, consistent API for creating GUIs to control various data types, that work across various environments.

GUIs may be built manually using a variety of widgets, or generated automatically from python type hints.

"},{"location":"#magicgui-organization","title":"magicgui organization","text":"

magicgui can be thought of as performing two distinct tasks:

  1. Providing an simplified abstraction layer for GUI frameworks, allowing you to use the same API to create UIs that can move between environments and frameworks (such as a desktop app, or a Jupyter notebook).
  2. Providing a mapping of python types to widgets, allowing you to autogenerate graphical user interfaces for functions and dataclasses by annotating with standard python type hints.

While there is some degree of customizeability, the emphasis is on rapid development of relatively simple GUIs, with minimal boilerplate. For highly customized GUIs with complex layouts, it may be more appropriate to use a lower-level GUI framework.

The API is organized into 2 main levels:

magicgui API layers"},{"location":"#python-type-mapping","title":"Python Type Mapping","text":"

At its highest level, magicgui provides a mapping of Python types to widgets. This API allows you to create graphical user interfaces for your functions and dataclasses simply by annotating them with standard python type hints.

Type hints??

Type hints are a way to annotate your code with information about the types of variables and function arguments. They are completely optional, but static type checkers and other libraries (like magicgui!) can use them to check your code and/or provide additional functionality.

Typically, they are provided after a colon following a variable name or function argument.

In the example below, param_a has been annotated as an int, param_b as a str, and the return value as a list.

def my_function(param_a: int, param_b: str) -> list:\n    ...\n

If you are new to type annotations in Python, here are a few resources to get you started:

"},{"location":"#create_widget","title":"create_widget","text":"

magicgui.widgets.create_widget is a general function, used throughout the library, that allows you to create a widget for a specific Python type or value:

from magicgui.widgets import create_widget\n\n# passing a type to create_widget\nwidget = create_widget(annotation=int)\nwidget.show()\n

# passing a value to create_widget\nwidget2 = create_widget(value=\"Hello World\")\nwidget2.show()\n

For more details on how magicgui maps types to widgets, see Type Mapping.

"},{"location":"#magicgui_1","title":"magicgui","text":"

The magicgui.magicgui function is one way to autogenerate a compound Widget based on the parameters of a function:

from typing import Annotated, Literal\n# for Python <= 3.8\n# from typing_extensions import Annotated\n# for Python <= 3.7\n# from typing_extensions import Annotated, Literal\n\nfrom magicgui import magicgui\n\n\n@magicgui\ndef my_function(\n    param_a: int,\n    param_b: Annotated[int, {'widget_type': \"Slider\", 'max': 100}] = 42,\n    param_c: Literal[\"First\", \"Second\", \"Third\"] = \"Second\"\n):\n    print(\"param_a:\", param_a)\n    print(\"param_b:\", param_b)\n    print(\"param_c:\", param_c)\n\n# my_function now IS a widget, in addition to being a callable function\nmy_function.show()\n

For more details on using magicgui and magic_factory, see the magicgui decorators page.

"},{"location":"#guiclass","title":"guiclass","text":"

magicgui.experimental.guiclass is a newer experimental feature that provides an object-oriented alternative to magicgui. It wraps dataclasses.dataclass and adds a gui attribute to the resulting class, which is a magicgui-generated widget that can be used to control the dataclass instance. (The widget is only created when the gui attribute is accessed for the first time.)

from magicgui.experimental import guiclass, button\n\n@guiclass\nclass MyDataclass:\n    a: int = 0\n    b: str = 'hello'\n    c: bool = True\n\n    @button\n    def compute(self):\n        print(self.a, self.b, self.c)\n\nobj = MyDataclass(a=10, b='foo')\nobj.gui.show()\n

For more details on using the guiclass decorator, see Dataclasses & guiclass.

"},{"location":"#widgets","title":"Widgets","text":"

At the lower level, magicgui is a library of widgets (the individual elements that make up a graphical user interface). Each widget is customized to display and interact with a specific type of data. In some cases, it makes more sense to create and arrange these widgets manually, rather than using the type-based autogeneration features described above.

Magicgui acts as an abstraction layer for a variety of different GUI toolkits, allowing you to use the same API to create UIs that can move between environments (such as a desktop app, or a Jupyter notebook).

Currently, magicgui supports the following backends:

You can use magicgui.widgets to quickly build graphical user interfaces.

from magicgui import widgets\n\na = widgets.SpinBox(value=10, label=\"a\")\nb = widgets.Slider(value=20, min=0, max=100, label=\"b\")\nresult = widgets.LineEdit(value=a.value * b.value, label=\"result\")\nbutton = widgets.PushButton(text=\"multiply\")\n\n@button.clicked.connect\ndef on_button_click():\n    result.value = a.value * b.value\n\ncontainer = widgets.Container(widgets=[a, b, result, button])\ncontainer.show()\n

To learn more about the available widgets and how to use them, see the Widgets Overview.

...details

Behind the scenes, magicgui declares a set of WidgetProtocols that each backend must implement, and every magicgui Widget is a wrapper around a backend-specific widget. Most users will never need to worry about this, but it's good to know that it's there if you ever need to dig deeper.

"},{"location":"#events","title":"Events","text":"

All widgets (whether created directly or autogenerated based on type hints) emit events when their value changes or in response to interaction.

To learn about connecting custom functionality to these events, see Events.

"},{"location":"#installation","title":"Installation","text":"

See installing magicgui.

"},{"location":"CONTRIBUTING/","title":"Contributing","text":"

Contributions are welcome!

"},{"location":"CONTRIBUTING/#development","title":"Development","text":"

To install magicgui for development, first clone the repository:

git clone https://github.com/pyapp-kit/magicgui\ncd magicgui\n

Then install the package in editable mode with the dev extra:

pip install -e .[dev]\n

To run the tests:

pytest\n
"},{"location":"CONTRIBUTING/#code-quality","title":"Code Quality","text":"

magicgui attempts to adhere to strict coding rules and employs the following static analysis tools to prevent errors from being introduced into the codebase:

To prevent continuous integration failures when contributing, please consider installing pre-commit in your environment to run all of these checks prior to checking in new code.

pre-commit install\n

To run the checks manually, you can use:

pre-commit run --all-files\n
"},{"location":"CONTRIBUTING/#adding-a-widget","title":"Adding a widget","text":"

These instructions may change in the future as the repo structures changes. If they appear outdated as you follow them, please open an issue.

To add a new widget, you will need to:

  1. Create a new class in magicgui/widgets/_concrete.py that inherits from the base class most appropriate for your widget (e.g. ValueWidget, or CategoricalWidget).

    In some (complex) cases, you may need to extend one of the base classes. If so, it is likely that you will also need to extend one of the Protocols found in magicgui.widgets.protocols. This is where all of protocols that backend classes need to implement to work with a given widget type. (Don't hesitate to open an issue if you're confused).

  2. Most likely, you will want to decorate the class with @backend_widget. Using this decorator implies that there is a class with the same name in any any backend modules that will support this widget type (e.g. magicgui.backends._qtpy.widgets for Qt support.).

  3. Make any changes necessary to your new concrete class. For example, you may need to change the value property and corresponding setter to handle a specific type. This part of the code should be backend agnostic.
  4. Export the new class in magicgui/widgets/__init__.py so that it can be imported from magicgui.widgets.
  5. Implement the backend widget class (using the same class name) in the appropriate backend module (e.g. magicgui.backends._qtpy.widgets for Qt support). Usually this will mean implementing the appropriate _mgui_get/set_... methods for the Protocol of the corresponding widget base class your chose to extend.
  6. Export the backend widget class in the __init__.py of the backend module (e.g. magicgui.backends._qtpy.__init__.py for Qt support). This is important, as that is where the @backend_widget decorator will look.
  7. Add a test for your new widget.

For an example of a minimal PR adding a new widget, see #483, which added a QuantityWidget to be used with pint.Quantity objects.

"},{"location":"CONTRIBUTING/#associating-a-widget-with-a-type","title":"Associating a widget with a type","text":"

To associate your new widget with a specific type such that it will be used when someone annotates a parameter with that type, you will need to update code in magicgui.type_map._type_map.

In the simplest of cases, this will mean adding a new entry to the magicgui.type_map._type_map._SIMPLE_TYPES dict. This is a mapping from a python type to a widget class. (Note that all subclasses of the type will also be matched.)

For more complex cases, you can add a new conditional to the body of the match_type function. That function should always return a tuple of widget type, and kwargs that will be passed to the widget constructor. For example: return widgets.MyNewWidget, {}.

"},{"location":"CONTRIBUTING/#building-the-documentation","title":"Building the documentation","text":"

To build the documentation locally, you will need to install the docs extra:

pip install -e .[docs]\n

Then, from the root of the repository, run:

mkdocs serve\n

This will start a local server at http://127.0.0.1:8000/ where you can view the documentation as you edit it.

"},{"location":"dataclasses/","title":"Dataclasses & guiclass","text":""},{"location":"dataclasses/#what-are-dataclasses","title":"What are dataclasses?","text":"

dataclasses are a feature added in Python 3.7 (PEP 557) that allow you to simply define classes that store a specific set of data. They encourage clear, type-annotated code, and are a great way to define data structures with minimal boilerplate.

New to dataclasses?

If you're totally new to dataclasses, you might want to start with the official documentation for the dataclasses module, or this Real Python post on dataclasses. The following is a very brief example of the key features:

Example dataclass
from dataclasses import dataclass\n\n@dataclass  # (1)!\nclass Person:\n    name: str # (2)!\n    age: int = 0  # (3)!\n\np = Person(name='John', age=30)  # (4)!\nprint(p) # (5)!\n
  1. The @dataclass decorator is used to mark a class as a dataclass. This will automatically generate an __init__ method with a parameter for each annotated class attribute.
  2. Attribute names are annotated with types. Note that, as with all Python type hints, these have no runtime effect (i.e. no validation is performed).
  3. Optional attributes can be defined with a default value. If no default value is specified, then the field is required when creating a new object.
  4. Creating a new object is as simple as passing in the required arguments.
  5. The __repr__ method is automatically generated and will print out the class name and all of the attributes and their current values.
"},{"location":"dataclasses/#dataclass-patterns-outside-the-standard-library","title":"dataclass patterns outside the standard library","text":"

The dataclasses module is not the only way to define data-focused classes in Python. There are other libraries that provide similar functionality, and some of them have additional features that are not available in the standard library.

"},{"location":"dataclasses/#magicgui-guiclass","title":"magicgui guiclass","text":"

Experimental

This is an experimental feature. The API may change in the future without deprecations or warnings.

magicgui supports the dataclass API as a way to define the interface for compound widget, where each attribute of the dataclass is a separate widget. The magicgui.experimental.guiclass decorator can be used to mark a class as a \"GUI class\". A GUI class is a Python standard dataclass that has two additional features:

  1. A property (named \"gui\" by default) that returns a Container widget which contains a widget for each attribute of the dataclass.
  2. An property (named \"events\" by default) that returns a psygnal.SignalGroup object that allows you to connect callbacks to the change event of any of field in the dataclass. (Under the hood, this uses the @evented dataclass decorator from psygnal.)

Tip

You can still use all of the standard dataclass features, including field values, __post_init__ processing, and ClassVar.

Info

In the future, we may also support other dataclass-like objects, such as pydantic models, attrs classes, and traitlets classes.

from magicgui.experimental import guiclass\n\n@guiclass\nclass MyDataclass:\n    a: int = 0\n    b: str = 'hello'\n    c: bool = True\n\nobj = MyDataclass()\nobj.gui.show()\n

The individual widgets in the Container may be accessed by the same name as the corresponding attribute. For example, obj.gui.a will return the SpinBox widget that controls the value of the a attribute.

"},{"location":"dataclasses/#two-way-data-binding","title":"Two-way data binding","text":"

As you interact programmatically with the obj instance, the widgets in the obj.gui will update. Similarly, as you change the value of the widgets in the obj.gui, the values of the obj instance will be updated.

obj = MyDataclass(a=10)\nobj.b = 'world'\nobj.c = False\n\nobj.gui.show()\n

All magicgui-related stuff is in the gui attribute

The original dataclass instance (obj) is essentially untouched. Just as in a regular dataclass, obj.a returns the current value of a in the dataclass. The widget for the class will be at obj.gui (or whatever name you specified in the gui_name parameter) So, obj.gui.a.value, returns the current value of the widget. Unless you explicitly disconnect the gui from the underlying object/model, the two will always be in sync.

"},{"location":"dataclasses/#adding-buttons-and-callbacks","title":"Adding buttons and callbacks","text":"

Buttons are one of the few widget types that tend not to have an associated value, but simply trigger a callback when clicked. That is: it doesn't often make sense to add a field to a dataclass representing a button. To add a button to a guiclass, decorate a method with the magicgui.experimental.button decorator.

positioning buttons

Currently, all buttons are appended to the end of the widget. The ability to position the button in the layout will be added in the future.

Any additional keyword arguments to the button decorator will be passed to the magicgui.widgets.PushButton constructor (e.g. label, tooltip, etc.)

from magicgui.experimental import guiclass, button\n\n@guiclass\nclass Greeter:\n    first_name: str\n\n    @button\n    def say_hello(self):\n        print(f'Hello {self.first_name}')\n\ngreeter = Greeter('Talley')\ngreeter.gui.show()\n

clicking the \"say_hello\" button will print \"Hello Talley\" to the console

Tip

As your widget begins to manage more internal state, the guiclass pattern becomes much more useful than the magicgui decorator pattern -- which was designed with pure functions that take inputs and return outputs in mind.

"},{"location":"decorators/","title":"magicgui & magic_factory","text":""},{"location":"decorators/#from-object-to-gui","title":"From Object to GUI","text":"

The eponymous feature of magicgui is the magicgui.magicgui function, which converts an object into a widget.

Info

Currently, the only supported objects are functions, but in the future magicgui.magicgui may accept other objects, such as dataclass instances

When used to decorate a function, @magicgui will autogenerate a graphical user interface (GUI) by inspecting the function signature and adding an appropriate GUI widget for each parameter, as described in Type Hints to Widgets. Parameter types are taken from type hints, if provided, or inferred using the type of the default value otherwise.

import math\nfrom enum import Enum\nfrom magicgui import magicgui\n\n# dropdown boxes are best made by creating an enum\nclass Medium(Enum):\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n# decorate your function with the @magicgui decorator\n@magicgui(call_button=\"calculate\")\ndef snells_law(aoi=30.0, n1=Medium.Glass, n2=Medium.Water, degrees=True):\n    aoi = math.radians(aoi) if degrees else aoi\n    try:\n        result = math.asin(n1.value * math.sin(aoi) / n2.value)\n        return math.degrees(result) if degrees else result\n    except ValueError:\n        # beyond the critical angle\n        return \"Total internal reflection!\"\n\nsnells_law.show()\n

The object returned by the magicgui decorator is an instance of magicgui.widgets.FunctionGui. It can still be called like the original function, but it also knows how to present itself as a GUI.

"},{"location":"decorators/#two-way-data-binding","title":"Two-Way Data Binding","text":"

The modified snells_law object gains attributes named after each of the parameters in the function. Each attribute is an instance of a magicgui.widgets.Widget subclass (suitable for the data type represented by that parameter). As you make changes in your GUI, the attributes of the snells_law object will be kept in sync. For instance, change the first dropdown menu from \"Glass\" to \"Oil\", and the corresponding n1 object on snells_law will change its value to 1.515:

snells_law.n1.value  # 1.515\n

It goes both ways: set a parameter in the console and it will change in the GUI:

snells_law.aoi.value = 47\nsnells_law.show()\n

"},{"location":"decorators/#its-still-a-function","title":"It's still a function","text":"

magicgui tries very hard to make it so that the decorated object behaves as much like the original object as possible.

We can invoke the function in a few ways:

"},{"location":"decorators/#connecting-events","title":"Connecting Events","text":""},{"location":"decorators/#function-calls","title":"Function Calls","text":"

With a GUI, you are usually looking for something to happen as a result of calling the function. The function will have a new called attribute that you can connect to an arbitrary callback function:

@snells_law.called.connect\ndef my_callback(value: str):\n    # The callback receives an `Event` object that has the result\n    # of the function call in the `value` attribute\n    print(f\"Your function was called! The result is: {value}\")\n\nresult = snells_law()\n

Now when you call snells_law(), or click the calculate button in the gui, my_callback will be called with the result of the calculation.

"},{"location":"decorators/#parameter-changes","title":"Parameter Changes","text":"

You can also listen for changes on individual function parameters by connecting to the <parameter_name>.changed signal:

# whenever the current value for n1 changes, print it to the console:\n@snells_law.n1.changed.connect\ndef _on_n1_changed(x: Medium):\n    print(f\"n1 was changed to {x}\")\n\nsnells_law.n1.value = Medium.Air\n

Note

This signal will be emitted regardless of whether the parameter was changed in the GUI or via by directly setting the paramaeter on the gui instance.

"},{"location":"decorators/#usage-as-a-decorator-is-optional","title":"Usage As a Decorator is Optional","text":"

Remember: the @decorator syntax is just syntactic sugar. You don't have to use @magicgui to decorate your function declaration. You can also just call it with your function as an argument:

This decorator usage:

@magicgui(auto_call=True)\ndef function():\n    pass\n

is equivalent to this:

def function():\n    pass\n\nfunction = magicgui(function, auto_call=True)\n

In many cases, it will actually be desirable not to use magicgui as a decorator if you don't need a widget immediately, but want to create one later (see also the magic_factory decorator.)

# some time later...\nwidget_instance = magicgui(function)\n
"},{"location":"decorators/#magic_factory","title":"magic_factory","text":"

The magicgui.magic_factory function/decorator acts very much like the magicgui decorator, with one important difference:

Unlike magicgui, magic_factory does not return a widget instance immediately. Instead, it returns a \"factory function\" that can be called to create a widget instance.

This is an important distinction to understand. In most cases, the @magicgui decorator is useful for interactive use or rapid prototyping. But if you are writing a library or package where someone else will be instantiating your widget (a napari plugin is a good example), you will likely want to use magic_factory instead, (or create your own Widget Container subclass).

it's just a partial

If you're familiar with functools.partial, you can think of magic_factory as a partial function application of the magicgui decorator (in fact, magic_factory is a subclass of partial). It is very roughly equivalent to:

def magic_factory(func, *args, **kwargs):\n    return partial(magicgui, func, *args, **kwargs)\n
"},{"location":"decorators/#widget_init","title":"widget_init","text":"

magic_factory gains one additional parameter: widget_init. This accepts a callable that will be called with the new widget instance each time the factory is called. This is a convenient place to add additional initialization or connect events.

from magicgui import magic_factory\n\ndef _on_init(widget):\n    print(\"widget created!\", widget)\n    widget.y.changed.connect(lambda x: print(\"y changed!\", x))\n\n@magic_factory(widget_init=_on_init)\ndef my_factory(x: int, y: str): ...\n\nnew_widget = my_factory()\n
"},{"location":"decorators/#the-lack-of-magic-in-magicgui","title":"The (lack of) \"magic\" in magicgui","text":"

Just to demystify the name a bit, there really isn't a whole lot of \"magic\" in the magicgui decorator. It's really just a thin wrapper around the magicgui.widgets.create_widget function, to create a Container with a sub-widget for each parameter in the function signature.

The widget creation is very roughly equivalent to something like this:

from inspect import signature, Parameter\nfrom magicgui.widgets import create_widget, Container\nfrom magicgui.types import Undefined\n\n\ndef pseudo_magicgui(func: 'Callable'):\n    return Container(\n        widgets=[\n            create_widget(p.default, annotation=p.annotation, name=p.name)\n            for p in signature(func).parameters.values()\n        ]\n    )\n\ndef some_func(x: int = 2, y: str = 'hello'):\n    return x, y\n\nmy_widget = pseudo_magicgui(some_func)\nmy_widget.show()\n

In the case of magicgui, a special subclass of Container (FunctionGui) is used, which additionally adds a __call__ method that allows the widget to behave like the original function.

"},{"location":"events/","title":"Events","text":"

All magicgui widgets emit events when certain properties change. For each event there is a corresponding signal attribute on the widget that can be connected to a callback function. For example, a PushButton emits an event when it is clicked, and all ValueWidget subclasses (like Slider or LineEdit) emit an event when their value changes.

"},{"location":"events/#connecting-to-events","title":"Connecting to events","text":"

To connect a callback to an event, use the connect method of the signal attribute. The exact signals available on each widget are mostly defined in the base classes, and are listed on the API page for each respective widget.

For example, to connect a callback to a LineEdit widget's changed event:

Widget APImagicgui decoratormagic_factory decorator
from magicgui import widgets\n\ntext = widgets.LineEdit(value='type something')\ntext.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n
from magicgui import magicgui\n\n@magicgui\ndef my_function(text: str):\n    ...\n\nmy_function.text.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n
from magicgui import magic_factory\n\ndef _on_init(widget):\n    widget.text.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n\n@magic_factory(widget_init=_on_init)\ndef my_function(text: str):\n    ...\n\nmy_widget = my_function()\n

It's all psygnal under the hood

magicgui uses psygnal for its event system. For greater detail on the connect method and its options, see the Usage section of psygnal's documentation, or the psygnal.SignalInstance.connect API reference.

Tip

Note that connect returns the callable that it was passed, so you can use it as a decorator if you prefer.

text = widgets.LineEdit(value='type something')\n\n# this works\ntext.changed.connect(lambda val: print(f\"Text changed to: {val}\"))\n\n# so does this\n@text.changed.connect\ndef on_text_changed(val):\n    print(f\"Text changed to: {val}\")\n
"},{"location":"installation/","title":"Installation","text":"

magicgui is a pure Python package, and can be installed with pip:

pip install magicgui\n

or with conda:

conda install -c conda-forge magicgui\n
"},{"location":"installation/#backends","title":"Backends","text":"

magicgui requires a backend to be installed in order to function, but it does not specify a particular backend by default. The following backends are available:

Important

Note not all widgets are necessarily implemented for all backends. Most widgets in the widget docs specify which backends are supported.

"},{"location":"installation/#extras","title":"Extras","text":"

The Image widget requires pillow. You may use the image extra:

pip install magicgui[image]\n

The magicgui.tqdm module requires tqdm. You may use the tqdm extra:

pip install magicgui[tqdm]\n

The QuantityEdit widget requires pint. You may use the quantity extra:

pip install magicgui[quantity]\n
"},{"location":"type_map/","title":"Type Hints to Widgets","text":"

One of the key offerings of magicgui is the ability to automatically generate Widgets from Python type hints. This page describes how type hints are mapped to Widgets, and how to customize that mapping.

"},{"location":"type_map/#default-type-mapping","title":"Default Type Mapping","text":"

By default, The following python Type Hint annotations are mapped to the corresponding Widget class, and parametrized with the corresponding kwargs (when applicable):

Type Hint Widget __init__ kwargs bool Slider int Slider float FloatSlider str LineEdit range RangeEdit slice SliceEdit list ListEdit tuple TupleEdit pathlib.Path FileEdit os.PathLike FileEdit Sequence[pathlib.Path] FileEdit {'mode': 'rm'} datetime.time TimeEdit datetime.timedelta TimeEdit datetime.date DateEdit datetime.datetime DateTimeEdit Literal['a', 'b'] ComboBox {'choices': ['a', 'b']} Set[Literal['a', 'b']] Select {'choices': ('a', 'b')} enum.Enum ComboBox {'choices': <enum 'Enum'>} magicgui.widgets.ProgressBar ProgressBar {'bind': <function match_type.<locals>.<lambda> at 0x13a9faa20>, 'visible': True} types.FunctionType FunctionGui {'function': ...} pint.Quantity QuantityEdit"},{"location":"type_map/#example","title":"Example","text":"

from magicgui import widgets\nimport pathlib\nimport os\nimport datetime\nfrom typing import Literal, Set, Sequence\nimport types\nimport pint\nimport enum\n\ntypes = [\n    bool, int, float, str, range, slice, list,\n    pathlib.Path, os.PathLike, Sequence[pathlib.Path],\n    datetime.time, datetime.timedelta, datetime.date, datetime.datetime,\n    Literal['a', 'b'], Set[Literal['a', 'b']], enum.Enum,\n    widgets.ProgressBar, pint.Quantity,\n]\n\nwdg = widgets.Container(\n    widgets=[\n        widgets.create_widget(annotation=t, label=str(t)) for t in types\n    ]\n)\nwdg.show()\n

"},{"location":"type_map/#customizing-widget-options-with-typingannotated","title":"Customizing Widget Options with typing.Annotated","text":"

Widget options and types may be embedded in the type hint itself using typing.Annotated.

Note

This is not the only way to customize the widget type or options in magicgui. Some functions (like magicgui.magicgui) also accept **param_options keyword arguments that map parameter names to dictionaries of widget options.

"},{"location":"type_map/#overriding-the-default-type","title":"Overriding the Default Type","text":"

To override the widget class used for a given object type, use the widget_type key in the Annotated kwargs. It can be either the string name of one of the built-in widgets, or any Widget subclass object.

Type Hint Widget __init__ kwargs Annotated[int, {'widget_type': 'Slider'}] Slider Annotated[float, {'widget_type': 'FloatSlider'}] FloatSlider"},{"location":"type_map/#overriding-the-default-options","title":"Overriding the Default Options","text":"

Any additional kwargs will be passed to the widget constructor (and must be valid for the corresponding widget type).

Type Hint Widget __init__ kwargs Annotated[int, {'step': 10, 'max': 50}] Slider {'step': 10, 'max': 50} Annotated[int, {'choices': [1, 2, 3]}] Slider {'choices': [1, 2, 3]}"},{"location":"type_map/#examples","title":"Examples","text":"

Create a widget using standard type map:

create_widgetmagicgui decoratorguiclass decorator
my_widget = widgets.create_widget(value=42, annotation=int)\n
from magicgui import magicgui\n\n@magicgui\ndef my_widget(x: int = 42):\n    return x\n
from magicgui.experimental import guiclass\n\n@guiclass\nclass MyObject:\n    x: int = 42\n\nobj = MyObject()\nmy_widget = obj.gui\n

Customize a widget using typing.Annotated:

create_widgetmagicgui decoratorguiclass decorator
from typing import Annotated\n\nInt10_50 = Annotated[int, (('widget_type', 'Slider'),('step', 10),('max', 50))]\nwdg2 = widgets.create_widget(value=42, annotation=Int10_50)\n
from magicgui import magicgui\nfrom typing import Annotated\n\nInt10_50 = Annotated[int, (('widget_type', 'Slider'),('step', 10),('max', 50))]\n\n@magicgui\ndef my_widget(x: Int10_50 = 42):\n    ...\n
from magicgui.experimental import guiclass\nfrom typing import Annotated\n\nInt10_50 = Annotated[int, (('widget_type', 'Slider'),('step', 10),('max', 50))]\n\n@guiclass\nclass MyObject:\n    x: Int10_50 = 42\n\nobj = MyObject()\nmy_widget = obj.gui\n

Note that you may also customize widget creation with kwargs to create_widget

from typing import Annotated\nfrom magicgui.widgets import Slider\n\noptions = {'step': 10, 'max': 50}\nwdg3 = widgets.create_widget(value=42, widget_type=Slider, options=options)\nwdg3.show()\n

... or to the magicgui decorator:

@magicgui(x={'widget_type': 'Slider', 'step': 10, 'max': 50})\ndef my_widget(x: int = 42):\n    ...\n\nmy_widget.show()\n

"},{"location":"type_map/#return-type-mapping","title":"Return Type Mapping","text":"

In some cases, magicgui may be able to create a widget for the return annotation of a function.

... more to come ...

"},{"location":"type_map/#postponed-annotations","title":"Postponed annotations","text":"

Using forward references and __future__.annotations with magicgui is possible, but requires some extra care. Read on for more details.

"},{"location":"type_map/#forward-references","title":"Forward References","text":"

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later. This is called a Forward Reference (see PEP 484). This is useful when you want to use a type hint that refers to a type that has not yet been defined, or when you want to avoid importing a type that is only used in a type hint.

from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from mymodule import MyType\n\ndef my_function(x: 'MyType') -> None:\n    ...\n
"},{"location":"type_map/#__future__annotations","title":"__future__.annotations","text":"

In Python 3.7, the __future__.annotations feature was introduced (PEP 563), which postpones the evaluation of type annotations. The effect of this is that no type annotations will be evaluated at definition time, and all type annotations will be treated as strings (regardless of whether they are enclosed in quotes or not).

from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from mymodule import MyType\n\n# no longer necessary to use quotes around 'MyType'\ndef my_function(x: MyType) -> None:\n    ...\n

While this is a useful feature for developers, it does make it significantly more difficult to use those type annotations at runtime.

Magicgui does attempt to resolve forward references it encounters (see Resolving type hints at runtime for gory details), but this is an imperfect process, and may not always work.

"},{"location":"type_map/#if-you-must-use-postponed-annotations","title":"If You Must Use Postponed Annotations","text":"

As a general rule, if you must use forward references or __future__.annotations in a module that uses magicgui, you should:

"},{"location":"type_map/#registering-support-for-custom-types","title":"Registering Support for Custom Types","text":"

Any third-party library may use the magicgui.register_type function to register its types with magicgui. When a registered type is used as an annotation, the registered widget will be used.

"},{"location":"type_map/#known-third-party-support-for-magicgui","title":"Known Third-Party Support for magicgui","text":"

Hi developer!

Have a library that registers types with magicgui? Let us know and we'll add it to this list!

"},{"location":"type_map/#napari","title":"napari","text":"

napari has registered a number of its types to provide access to napari-specific objects using type annotations in magicgui. Details may be found in napari's documentation on using magicgui in napari.

"},{"location":"widgets/","title":"Widgets","text":"

Tip

If you're looking for an index of all available widgets, see the Widget Index.

All individual graphical elements in magicgui are \"widgets\", and all widgets are instances of magicgui.widgets.Widget. Widgets may be created directly:

from magicgui.widgets import LineEdit\n\nline_edit = LineEdit(value='hello!')\nline_edit.show()\n

Some widgets (such as magicgui.widgets.Container) are composite widgets that comprise other widgets:

from magicgui.widgets import LineEdit, SpinBox, Container\n\nline_edit = LineEdit(value='hello!')\nspin_box = SpinBox(value=400)\ncontainer = Container(widgets=[line_edit, spin_box])\ncontainer.show()\n

magicgui provides a way to automatically select a widget given a python value or type annotation using magicgui.widgets.create_widget. Here is an example that yields the same result as the one above:

from magicgui.widgets import create_widget\n\nx = 'hello!'\ny = 400\ncontainer = Container(widgets=[create_widget(i) for i in (x, y)])\ncontainer.show()\n

Tip

Because there are often multiple valid widget types for a given python object, you may sometimes wish to create widgets directly, or use the widget_type argument in create_widget()

"},{"location":"widgets/#the-widget-hierarchy","title":"The widget hierarchy","text":"
graph TB\n    A([Widget])-->B([ValueWidget])\n    A-->C([ContainerWidget])\n    B-->D([RangedWidget])\n    B-->E([ButtonWidget])\n    B-->F([CategoricalWidget])\n    C-->H([MainWindowWidget])\n    C-->G([FunctionGui])\n    D-->I([SliderWidget])\n    click A \"#widget\"\n    click B \"#valuewidget\"\n    click C \"#containerwidget\"\n    click D \"#rangedwidget\"\n    click E \"#buttonwidget\"\n    click F \"#categoricalwidget\"\n    click H \"#mainwindowwidget\"\n    click G \"#functiongui\"\n    click I \"#sliderwidget\"

Many widgets present similar types of information in different ways. magicgui tries to maintain a consistent API among all types of widgets that are designed to represent similar objects. The general class of widget you are working with will determine the properties and attributes it has.

Note

The categories shown below are sorted by their base class (such as ValueWidget and RangedWidget). The bases are not intended to be instantiated directly. Instead, you would create the widget type you wanted, such as LineEdit or SpinBox, respectively.

"},{"location":"widgets/#widget","title":"Widget","text":"

As mentioned above, all magicgui widgets derive from magicgui.widgets.Widget and have the following attributes (this list is not comprehensive, see the magicgui.widgets.Widget API):

Attribute Type Description name str The name or \"ID\" of this widget (such as a function parameter name to which this widget corresponds). annotation Any A type annotation for the value represented by the widget. label str A string to use for an associated Label widget (if this widget is being shown in a magicgui.widgets.Container widget, and container.labels is True). By default, name will be used. Note: name refers the name of the parameter, as might be used in a signature, whereas label is just the label for that widget in the GUI. tooltip str A tooltip to display when hovering over the widget. visible bool Whether the widget is visible."},{"location":"widgets/#valuewidget","title":"ValueWidget","text":"

In addition to the base Widget properties mentioned above, the following ValueWidgets track some value:

Widget Description Label A non-editable text display. LineEdit A one-line text editor. LiteralEvalLineEdit A one-line text editor that evaluates strings as python literals. Password A one-line text editor that obscures input. TextEdit A widget to edit and display both plain and rich text. FileEdit A LineEdit widget with a button that opens a FileDialog. RangeEdit A widget to represent a python range object, with start/stop/step. SliceEdit A widget to represent slice objects, with start/stop/step. DateTimeEdit A widget for editing dates and times. DateEdit A widget for editing dates. TimeEdit A widget for editing times. Table A widget to represent columnar or 2D data with headers. QuantityEdit A combined LineEdit and ComboBox to edit a pint.Quantity. Attribute Type Description value Any The current value of the widget. changed psygnal.SignalInstance A psygnal.SignalInstance that will emit an event when the value has changed. Connect callbacks to the change event using widget.changed.connect(callback) bind Any, optional A value or callback to bind this widget. If bound, whenever widget.value is accessed, the value provided here will be returned. The bound value can be a callable, in which case bound_value(self) will be returned (i.e. your callback must accept a single parameter, which is this widget instance.). see ValueWidget.bind for details.

Here is a demonstration of all these:

from magicgui import widgets\nimport datetime\n\nwdg_list = [\n    widgets.Label(value=\"label value\", label=\"Label:\"),\n    widgets.LineEdit(value=\"line edit value\", label=\"LineEdit:\"),\n    widgets.Password(value=\"super-secret!\", label=\"Password:\"),\n    widgets.TextEdit(value=\"text edit value...\", label=\"TextEdit:\"),\n    widgets.FileEdit(value=\"/home\", label=\"FileEdit:\"),\n    widgets.RangeEdit(value=range(0, 10, 2), label=\"RangeEdit:\"),\n    widgets.SliceEdit(value=slice(0, 10, 2), label=\"SliceEdit:\"),\n    widgets.DateTimeEdit(\n      value=datetime.datetime(1999, 12, 31, 11, 30), label=\"DateTimeEdit:\"\n    ),\n    widgets.DateEdit(value=datetime.date(81, 2, 18), label=\"DateEdit:\"),\n    widgets.TimeEdit(value=datetime.time(12, 20), label=\"TimeEdit:\"),\n    widgets.QuantityEdit(value='12 seconds', label=\"Quantity:\")\n]\ncontainer = widgets.Container(widgets=wdg_list)\ncontainer.max_height = 300\ncontainer.show()\n

"},{"location":"widgets/#rangedwidget","title":"RangedWidget","text":"

RangedWidgets are numerical ValueWidgets that have a restricted range of valid values, and a step size. RangedWidgets include:

Widget Description SpinBox A widget to edit an integer with clickable up/down arrows. FloatSpinBox A widget to edit a float with clickable up/down arrows.

In addition to all of the ValueWidget attributes, RangedWidget attributes include:

Attribute Type Description min float The minimum allowable value, by default 0 max float The maximum allowable value, by default 1000 step float The step size for incrementing the value, by default 1 range tuple of float A convenience attribute for getting/setting the (min, max) simultaneously

w1 = widgets.SpinBox(value=10, max=20, label='SpinBox:')\nw2 = widgets.FloatSpinBox(value=380, step=0.5, label='FloatSpinBox:')\ncontainer = widgets.Container(widgets=[w1, w2])\ncontainer.show()\n

"},{"location":"widgets/#sliderwidget","title":"SliderWidget","text":"

SliderWidgets are special RangedWidgets that additionally have an orientation, and a readout.

Widget Description Slider A slider widget to adjust an integer value within a range. FloatSlider A slider widget to adjust an integer value within a range. LogSlider A slider widget to adjust a numerical value logarithmically within a range. ProgressBar A progress bar widget.

In addition to all of the RangedWidget attributes, SliderWidget attributes include:

Attribute Type Description orientation str The orientation for the slider. Must be either 'horizontal' or 'vertical'. by default 'horizontal' readout bool Whether to show the value of the slider. By default, True.

w1 = widgets.Slider(value=10, max=25, label='Slider:')\nw2 = widgets.FloatSlider(value=10.5, max=18.5, label='FloatSlider:')\nw3 = widgets.ProgressBar(value=80, max=100, label='ProgressBar:')\ncontainer = widgets.Container(widgets=[w1, w2, w3])\ncontainer.show()\n

"},{"location":"widgets/#buttonwidget","title":"ButtonWidget","text":"

ButtonWidgets are boolean ValueWidgets that also have some text associated with them.

Widget Description PushButton A clickable command button. CheckBox A checkbox with a text label.

In addition to all of the ValueWidget attributes, ButtonWidget attributes include:

Attribute Type Description text str The text to display on the button. If not provided, will use name.

w1 = widgets.PushButton(value=True, text='PushButton Text')\nw2 = widgets.CheckBox(value=False, text='CheckBox Text')\ncontainer = widgets.Container(widgets=[w1, w2])\ncontainer.show()\n

"},{"location":"widgets/#categoricalwidget","title":"CategoricalWidget","text":"

CategoricalWidget are ValueWidgets that provide a set of valid choices. They can be created from:

Widget Description ComboBox A dropdown menu, allowing selection between multiple choices. RadioButtons An exclusive group of radio buttons, providing a choice from multiple choices. Select A list of options, allowing selection between multiple choices.

In addition to all of the ValueWidget attributes, CategoricalWidget attributes include:

Attribute Type Description choices Enum, Iterable, or Callable Available choices displayed in the widget. value Any In the case of a CategoricalWidget the value is the data of the currently selected choice (see also: current_choice below). current_choice str The name associated with the current choice. For instance, if choices was provided as choices=[('one', 1), ('two', 2)], then an example value would be 1, and an example current_choice would be 'one'.

choices = ['one', 'two', 'three']\nw1 = widgets.ComboBox(choices=choices, value='two', label='ComboBox:')\nw2 = widgets.RadioButtons(choices=choices, label='RadioButtons:')\nw3 = widgets.Select(choices=choices, label='Select:')\ncontainer = widgets.Container(widgets=[w1, w2, w3])\ncontainer.max_height = 220\ncontainer.show()\n

"},{"location":"widgets/#containerwidget","title":"ContainerWidget","text":"

A ContainerWidget is a list-like Widget that can contain other widgets. Containers allow you to build more complex widgets from sub-widgets. A notable example of a Container is magicgui.widgets.FunctionGui) (the product of the @magicgui decorator).

Widget Description Container A Widget to contain other widgets. MainWindow A Widget to contain other widgets, includes a menu bar. FunctionGui Wrapper for a container of widgets representing a callable object. Attribute Type Description layout str The layout for the container. Must be either 'horizontal' or 'vertical'. widgets Sequence[Widget] The widgets that the container contains. labels bool Whether each widget should be shown with a corresponding Label widget to the left. Note: the text for each widget defaults to widget.name, but can be overridden by setting widget.label.

Container implements the full collections.abc.MutableSequence interface. You can add and remove widgets from it just as you would add or remove items from a list.

from magicgui.widgets import Container, Slider, FloatSlider, ProgressBar\n\ncontainer = widgets.Container()\ncontainer.append(widgets.LineEdit(value='Mookie', label='Your Name:'))\ncontainer.append(widgets.FloatSlider(value=10.5, label='FloatSlider:'))\ncontainer.show()\n

"},{"location":"widgets/#mainwindowwidget","title":"MainWindowWidget","text":"

A MainWindowWidget is a special type of ContainerWidget that also includes a menu bar.

"},{"location":"widgets/#functiongui","title":"FunctionGui","text":"

A FunctionGui is a special type of ContainerWidget that is created from a function. It is the product of the @magicgui decorator. It is a container that contains a widget for each of the parameters in the function. See magicgui.widgets.FunctionGui for details.

"},{"location":"widgets/#magicgui","title":"@magicgui","text":"

It's worth noting that @magicgui and @magic_factory decorators are just conveniences that build a special type of Container widget (a FunctionGui), with a widget representing each of the parameters in a decorated function.

from magicgui import magicgui\n\n@magicgui\ndef my_function(x='hello', y=400): ...\n\nmy_function.show()\n

In terms of simply building widgets, the following code performs a similar task to @magicgui.

from inspect import signature\n\ndef my_function(x='hello', y=400):\n  ...\n\nparams = signature(my_function).parameters.values()\ncontainer = Container(\n    widgets=[create_widget(p.default, name=p.name) for p in params]\n)\ncontainer.show()\n

Tip

Note that the FunctionGui widget produced by @magicgui is actually a callable object that behaves very much like the original function, except that it will use current values from the GUI as default parameters when calling the function.

"},{"location":"api/app/","title":"Application","text":""},{"location":"api/app/#magicgui.application.Application","title":"magicgui.application.Application","text":"

Magicgui Application, wrapping a native BaseApplicationBackend implementation.

"},{"location":"api/app/#magicgui.application.Application.backend_module","title":"backend_module: ModuleType property","text":"

Return module object that defines the backend.

"},{"location":"api/app/#magicgui.application.Application.backend_name","title":"backend_name: str property","text":"

Return name of the GUI backend that this app wraps.

"},{"location":"api/app/#magicgui.application.Application.native","title":"native: Any property","text":"

Return the native GUI application instance.

"},{"location":"api/app/#magicgui.application.Application.__enter__","title":"__enter__() -> Application","text":"

Context manager to start this application.

"},{"location":"api/app/#magicgui.application.Application.__exit__","title":"__exit__(*exc_details: Any) -> None","text":"

Exit context manager for this application.

"},{"location":"api/app/#magicgui.application.Application.__repr__","title":"__repr__() -> str","text":"

Return repr for this instance.

"},{"location":"api/app/#magicgui.application.Application.create","title":"create() -> None","text":"

Create the native application.

"},{"location":"api/app/#magicgui.application.Application.get_obj","title":"get_obj(name: str) -> Any","text":"

Get the backend object for the given name (such as a widget).

"},{"location":"api/app/#magicgui.application.Application.process_events","title":"process_events() -> None","text":"

Process all pending GUI events.

"},{"location":"api/app/#magicgui.application.Application.quit","title":"quit() -> None","text":"

Quit the native GUI event loop.

"},{"location":"api/app/#magicgui.application.Application.run","title":"run() -> None","text":"

Enter the native GUI event loop.

"},{"location":"api/app/#magicgui.application.Application.start_timer","title":"start_timer(interval: int = 1000, on_timeout: Callable[[], None] | None = None, single_shot: bool = False) -> None","text":"

Start a timer with a given interval, optional callback, and single_shot.

"},{"location":"api/app/#magicgui.application.use_app","title":"magicgui.application.use_app(app: AppRef | None = None) -> Application","text":"

Get/create the default Application object. See _use_app docstring.

"},{"location":"api/experimental/","title":"magicgui.experimental","text":"

Experimental

This module contains experimental features that are not yet ready for prime time. All of the features in this module are subject to change without warning or deprecation.

"},{"location":"api/experimental/#magicgui.experimental.guiclass","title":"magicgui.experimental.guiclass(cls: T | None = None, *, gui_name: str = 'gui', events_namespace: str = 'events', follow_changes: bool = True, **dataclass_kwargs: Any) -> T | Callable[[T], T]","text":"

Turn class into a dataclass with a property (gui_name) that returns a gui.

This decorator is similar to dataclasses.dataclass, but it will also add an events attribute to the class that is an instance of psygnal.SignalGroup (with a signal for each field in the dataclass; see https://psygnal.readthedocs.io/en/latest/dataclasses/ for details), and a gui property that returns a magicgui widget, bound to the values of the dataclass instance.

Note

This decorator is compatible with dataclasses using slots=True, however, there is a potential for a memory leak that the user should be aware of. If you create a guiclass instance, and then store a reference to its gui, and then delete the instance, the gui will still be bound to the instance, preventing it from being garbage collected. To avoid this, you can call unbind_gui_from_instance(gui, instance) before deleting the instance.

Parameters:

Returns:

Examples:

>>> @guiclass\n... class MyData:\n...     x: int = 0\n...     y: str = 'hi'\n...\n...     @button\n...     def reset(self):\n...         self.x = 0\n...         self.y = 'hi'\n...\n>>> data = MyData()\n>>> data.gui.show()\n
"},{"location":"api/experimental/#magicgui.experimental.button","title":"magicgui.experimental.button(func: F | None = None, **button_kwargs: Any) -> F | Callable[[F], F]","text":"

Add a method as a button to a guiclass, which calls the decorated method.

Parameters:

"},{"location":"api/experimental/#magicgui.experimental.is_guiclass","title":"magicgui.experimental.is_guiclass(obj: object) -> TypeGuard[GuiClassProtocol]","text":"

Return True if obj is a guiclass or an instance of a guiclass.

"},{"location":"api/magic_factory/","title":"magicgui.magic_factory","text":""},{"location":"api/magic_factory/#magicgui.magic_factory","title":"magicgui.magic_factory(function=None, *, layout='vertical', scrollable=False, labels=True, tooltips=True, call_button=None, auto_call=False, result_widget=False, main_window=False, app=None, persist=False, widget_init=None, raise_on_unknown=False, **param_options)","text":"

Return a MagicFactory for function.

magic_factory is nearly identical to the magicgui decorator with the following differences:

  1. Whereas magicgui returns a FunctionGui instance, magic_factory returns a callable that returns a FunctionGui instance. (Technically, it returns an instance of MagicFactory which you behaves exactly like a functools.partial for a FunctionGui instance.)
  2. magic_factory adds a widget_init method: a callable that will be called immediately after the FunctionGui instance is created. This can be used to add additional widgets to the layout, or to connect signals to the widgets.

Important

Whereas decorating a function with magicgui will immediately create a widget instance, magic_factory will not create a widget instance until the decorated object is called. This is often what you want in a library, whereas magicgui is useful for rapid, interactive development.

Parameters:

Returns:

Examples:

>>> @magic_factory\n... def my_function(a: int = 1, b: str = 'hello'):\n...     pass\n...\n>>> my_widget = my_function()\n>>> my_widget.show()\n>>> my_widget.a.value == 1  # True\n>>> my_widget.b.value = 'world'\n
"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory","title":"magicgui.type_map._magicgui.MagicFactory","text":"

Bases: partial, Generic[_FGuiVar]

Factory function that returns a FunctionGui instance.

While this can be used directly, (see example below) the preferred usage is via the magicgui.magic_factory decorator.

Examples:

>>> def func(x: int, y: str):\n...     pass\n...\n>>> factory = MagicFactory(function=func, labels=False)\n>>> # factory accepts all the same arguments as magicgui()\n>>> widget1 = factory(call_button=True)\n>>> # can also override magic_kwargs that were provided when creating the factory\n>>> widget2 = factory(auto_call=True, labels=True)\n
"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__name__","title":"__name__: str property","text":"

Pass function name.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__call__","title":"__call__(*args, **kwargs)","text":"

Call the wrapped _magicgui and return a FunctionGui.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__getattr__","title":"__getattr__(name)","text":"

Allow accessing FunctionGui attributes without mypy error.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__new__","title":"__new__(function, *args, magic_class=FunctionGui, widget_init=None, **keywords)","text":"

Create new MagicFactory.

"},{"location":"api/magic_factory/#magicgui.type_map._magicgui.MagicFactory.__repr__","title":"__repr__()","text":"

Return string repr.

"},{"location":"api/magicgui/","title":"magicgui.magicgui","text":""},{"location":"api/magicgui/#magicgui.magicgui","title":"magicgui.magicgui(function=None, *, layout='vertical', scrollable=False, labels=True, tooltips=True, call_button=None, auto_call=False, result_widget=False, main_window=False, app=None, persist=False, raise_on_unknown=False, **param_options)","text":"

Return a FunctionGui for function.

Parameters:

Returns:

Examples:

>>> @magicgui\n... def my_function(a: int = 1, b: str = 'hello'):\n...     pass\n...\n>>> my_function.show()\n>>> my_function.a.value == 1  # True\n>>> my_function.b.value = 'world'\n
"},{"location":"api/migration/","title":"migration guide","text":""},{"location":"api/migration/#v030-migration-guide","title":"v0.3.0 migration guide","text":"

October, 2021

Version 0.3.0 of magicgui introduced some changes to the events and callbacks API. See https://github.com/pyapp-kit/magicgui/pull/253 for details

"},{"location":"api/migration/#callbacks-now-receive-the-value-directly-instead-of-an-event-object","title":"Callbacks now receive the value directly, instead of an Event object","text":"

magicgui 0.3.0 is now using psygnal as its event/callback handler.

Callbacks connected to widget.changed (and other event emitters) may now receive the value(s) directly, instead of an event object:

\ud83d\udc4e Old Method (< v0.3.0)
@widget.changed.connect\ndef my_callback(event):\n    # event was an `Event` object with a `value` attribute\n    new_value = event.value\n

Existing code using callbacks with a single positional argument will continue to receive a single Event object (and a warning will be shown, until v0.4.0 where it will become an error).

To silence the warning and opt in to the new pattern of receiving value directly, you can do one of two things:

  1. type hint your single positional argument as anything other than magicgui.events.Event
  2. provide a callback that takes no arguments
\ud83d\udc4d New Method (>= v0.3.0)
@widget.changed.connect\ndef my_callback(new_value: int):\n    ...  # use new_value directly\n\n# or, if you don't need to use new_value\n@widget.changed.connect\ndef my_callback():\n    # something that didn't need the value\n    ...\n
"},{"location":"api/migration/#event-emitters-take-no-keyword-arguments","title":"Event emitters take no keyword arguments","text":"

For the few packages who were manually emitting change events, you should no longer provide the value= keyword when emitting.

\ud83d\udc4e Old Method (< v0.3.0)
widget.changed(value='whatever')\n
\ud83d\udc4d New Method (>= v0.3.0)
widget.changed.emit('whatever')\n# OR (if you prefer the direct __call__ syntax)\nwidget.changed('whatever')\n
"},{"location":"api/migration/#v020-migration-guide","title":"v0.2.0 migration guide","text":"

December, 2020

Version 0.2.0 of magicgui was a complete rewrite that introduced a couple breaking API changes

"},{"location":"api/migration/#gui-attribute-removed","title":".Gui() attribute removed","text":"

Before v0.2.0, the magicgui.magicgui decorator added a Gui attribute to the decorated function that was to be called to instantiate a widget. In v0.2.0 the object returned from the magicgui.magicgui decorator is already an instantiated magicgui.widgets.Widget.

\ud83d\udc4e Old Method (< v0.2.0)
from magicgui import magicgui, event_loop\n\n@magicgui\ndef function(x, y):\n    ...\n\nwith event_loop():\n    gui = function.Gui(show=True)\n
\ud83d\udc4d New Method (>= v0.2.0)
from magicgui import magicgui\n\n@magicgui\ndef function(x, y):\n    ...\n\nfunction.show(run=True)\n
"},{"location":"api/migration/#new-base-widget-type","title":"New base widget type","text":"

Before v0.2.0, the Gui() object returned by the magicgui.magicgui decorator was a MagicGuiBase widget class, which in turn was a direct subclass of a backend widget, such as a QtWidgets.QWidget. In v0.2.0, all widgets derive from [magicgui.widgets.Widget``][magicgui.widgets.Widget], and the *backend* is available atwidget.native. If you are incorporating magicgui widgets into a larger Qt-based GUI, please note that you will want to usewidget.nativeinstead ofwidget`

from magicgui import magicgui, use_app\n\nuse_app('qt')\n\n@magicgui\ndef function(x, y):\n    ...\n
>>> print(type(function))\n<class 'magicgui.widgets.FunctionGui'>\n>>> print(type(function.native))\n<class 'PyQt5.QtWidgets.QWidget'>\n
"},{"location":"api/migration/#starting-the-application","title":"Starting the application","text":"

It is now easier to show a widget and start an application by calling widget.show(run=True). Calling show(run=True) will immediately block execution of your script and show the widget. If you wanted to (for instance) show multiple widgets next to each other, then you would still want to use the event_loop context manager:

from magicgui import magicgui, event_loop\n\n@magicgui\ndef function_a(x=1, y=3):\n    ...\n\n@magicgui\ndef function_b(z='asdf'):\n    ...\n\nwith event_loop():\n    function_a.show()\n    function_b.show()\n# both widgets will show (though b may be on top of a)\n
"},{"location":"api/migration/#getting-and-setting-values","title":"Getting and setting values","text":"

To get or set the value of a widget programmatically, you no longer set the corresponding widget attribute directly, but rather use the widget.value attribute:

Old Method \ud83d\udc4e

gui.x used to be a descriptor object to get/set the value, but the actual underlying widget was at gui.x_widget

gui = function.Gui()\ngui.x = 10\n

New Method \ud83d\udc4d

now function.x IS the widget, and you set its value with function.x.value

function.x.value = 10\n
"},{"location":"api/migration/#connecting-callbacks-to-events","title":"Connecting callbacks to events","text":"

When binding callbacks to change events, you no longer connect to gui.<name>_changed, you now connect to function.<name>.changed:

\ud83d\udc4e Old Method (< v0.2.0)
gui = function.Gui()\ngui.x_changed.connect(my_callback)\n
\ud83d\udc4d New Method (>= v0.2.0)
function.x.changed.connect(my_callback)\n
"},{"location":"api/migration/#renamed","title":"Renamed","text":""},{"location":"api/protocols/","title":"Backend Protocols","text":"

Advanced Topic

Most users of magicgui will not need to worry about this section.

These Protocol classes declare the interface that backend adapters must implement in order to be used by magicgui. All magicgui Widget objects compose a backend widget implementing one of these protocols, and control it using the methods defined herein.

magicgui developers may be interested in this page, but end-users needn't worry about it.

"},{"location":"api/protocols/#summary","title":"Summary","text":"Widget Description WidgetProtocol Base Widget Protocol: specifies methods that all widgets must provide. ValueWidgetProtocol Widget that has a current value, with getter/setter and on_change callback. ButtonWidgetProtocol The \"value\" in a ButtonWidget is the current (checked) state. TableWidgetProtocol ValueWidget subclass intended for 2D tabular data, with row & column headers. RangedWidgetProtocol Value widget that supports numbers within a provided min/max range. CategoricalWidgetProtocol Categorical widget, that has a set of valid choices, and a current value. SliderWidgetProtocol Protocol for implementing a slider widget. ContainerProtocol Widget that can contain other widgets. BaseApplicationBackend Backend Application object. DialogProtocol Protocol for modal (blocking) containers. SupportsChoices Widget that has a set of valid choices. SupportsOrientation Widget that can be reoriented. SupportsText Widget that have text (in addition to value)... like buttons. SupportsReadOnly Widget that can be read_only."},{"location":"api/protocols/#protocol-inheritance","title":"Protocol Inheritance","text":"

The visual hierarchy of protocols looks like this:

graph LR\n    A([WidgetProtocol])-->B([ValueWidgetProtocol])\n    A-->C([ContainerProtocol])\n    M([SupportsText])-->E\n    B-->E([ButtonWidgetProtocol])\n    B-->D([RangedWidgetProtocol])\n    B-->F([CategoricalWidgetProtocol])\n    D-->I([SliderWidgetProtocol])\n    B-->J([TableWidgetProtocol])\n    K([SupportsReadOnly])-->J([TableWidgetProtocol])\n    L([SupportsChoices])-->F\n    N([SupportsOrientation])-->C\n    N-->I\n    C-->O([DialogProtocol])\n    C-->P([MainWindowProtocol])\n\n    click A \"#magicgui.widgets.protocols.WidgetProtocol\"\n    click B \"#magicgui.widgets.protocols.ValueWidgetProtocol\"\n    click C \"#magicgui.widgets.protocols.ContainerProtocol\"\n    click D \"#magicgui.widgets.protocols.RangedWidgetProtocol\"\n    click E \"#magicgui.widgets.protocols.ButtonWidgetProtocol\"\n    click F \"#magicgui.widgets.protocols.CategoricalWidgetProtocol\"\n    click I \"#magicgui.widgets.protocols.SliderWidgetProtocol\"\n    click J \"#magicgui.widgets.protocols.TableWidgetProtocol\"\n    click K \"#magicgui.widgets.protocols.SupportsReadOnly\"\n    click L \"#magicgui.widgets.protocols.SupportsChoices\"\n    click M \"#magicgui.widgets.protocols.SupportsText\"\n    click N \"#magicgui.widgets.protocols.SupportsOrientation\"\n    click O \"#magicgui.widgets.protocols.DialogProtocol\"\n    click P \"#magicgui.widgets.protocols.MainWindowProtocol\"
"},{"location":"api/protocols/#widget-protocols","title":"Widget Protocols","text":""},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol","title":"magicgui.widgets.protocols.WidgetProtocol","text":"

Bases: Protocol

Base Widget Protocol: specifies methods that all widgets must provide.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_bind_parent_change_callback","title":"_mgui_bind_parent_change_callback(callback: Callable[[Any], None]) -> None abstractmethod","text":"

Bind callback to parent change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_close_widget","title":"_mgui_close_widget() -> None abstractmethod","text":"

Close widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_enabled","title":"_mgui_get_enabled() -> bool abstractmethod","text":"

Get the enabled state of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_height","title":"_mgui_get_height() -> int abstractmethod","text":"

Get the height of the widget.

The intention is to get the height of the widget after it is shown, for the purpose of unifying widget height in a layout. Backends may do what they need to accomplish this. For example, Qt can use sizeHint().height(), since height() may return something large if the widget has not yet been painted on screen.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_max_height","title":"_mgui_get_max_height() -> int abstractmethod","text":"

Get the maximum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_max_width","title":"_mgui_get_max_width() -> int abstractmethod","text":"

Get the maximum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_min_height","title":"_mgui_get_min_height() -> int abstractmethod","text":"

Get the minimum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_min_width","title":"_mgui_get_min_width() -> int abstractmethod","text":"

Get the minimum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_native_widget","title":"_mgui_get_native_widget() -> Any abstractmethod","text":"

Return the native backend widget instance.

This is generally the widget that has the layout.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_parent","title":"_mgui_get_parent() -> Widget abstractmethod","text":"

Return the parent widget of this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_root_native_widget","title":"_mgui_get_root_native_widget() -> Any abstractmethod","text":"

Return the root native backend widget.

In most cases, this is the same as _mgui_get_native_widget. However, in cases where the native widget is in a scroll layout, this might be different.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_tooltip","title":"_mgui_get_tooltip() -> str abstractmethod","text":"

Get the tooltip for this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_visible","title":"_mgui_get_visible() -> bool abstractmethod","text":"

Get widget visibility.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_get_width","title":"_mgui_get_width() -> int abstractmethod","text":"

Get the width of the widget.

The intention is to get the width of the widget after it is shown, for the purpose of unifying widget width in a layout. Backends may do what they need to accomplish this. For example, Qt can use sizeHint().width(), since width() may return something large if the widget has not yet been painted on screen.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_render","title":"_mgui_render() -> np.ndarray abstractmethod","text":"

Return an RGBA (MxNx4) numpy array bitmap of the rendered widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_enabled","title":"_mgui_set_enabled(enabled: bool) -> None abstractmethod","text":"

Set the enabled state of the widget to enabled.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_height","title":"_mgui_set_height(value: int) -> None abstractmethod","text":"

Set the height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_max_height","title":"_mgui_set_max_height(value: int) -> None abstractmethod","text":"

Set the maximum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_max_width","title":"_mgui_set_max_width(value: int) -> None abstractmethod","text":"

Set the maximum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_min_height","title":"_mgui_set_min_height(value: int) -> None abstractmethod","text":"

Set the minimum height of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_min_width","title":"_mgui_set_min_width(value: int) -> None abstractmethod","text":"

Set the minimum width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_parent","title":"_mgui_set_parent(widget: Widget) -> None abstractmethod","text":"

Set the parent widget of this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_tooltip","title":"_mgui_set_tooltip(value: str | None) -> None abstractmethod","text":"

Set a tooltip for this widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_visible","title":"_mgui_set_visible(value: bool) -> None abstractmethod","text":"

Set widget visibility.

"},{"location":"api/protocols/#magicgui.widgets.protocols.WidgetProtocol._mgui_set_width","title":"_mgui_set_width(value: int) -> None abstractmethod","text":"

Set the width of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol","title":"magicgui.widgets.protocols.ValueWidgetProtocol","text":"

Bases: WidgetProtocol, Protocol

Widget that has a current value, with getter/setter and on_change callback.

It is worth noting that the widget is the thing that has a value. Magicgui does not maintain & synchronize an independent model.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol._mgui_bind_change_callback","title":"_mgui_bind_change_callback(callback: Callable[[Any], Any]) -> None abstractmethod","text":"

Bind callback to value change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol._mgui_get_value","title":"_mgui_get_value() -> Any abstractmethod","text":"

Get current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ValueWidgetProtocol._mgui_set_value","title":"_mgui_set_value(value: Any) -> None abstractmethod","text":"

Set current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ButtonWidgetProtocol","title":"magicgui.widgets.protocols.ButtonWidgetProtocol","text":"

Bases: ValueWidgetProtocol, SupportsText, SupportsIcon, Protocol

The \"value\" in a ButtonWidget is the current (checked) state.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol","title":"magicgui.widgets.protocols.TableWidgetProtocol","text":"

Bases: ValueWidgetProtocol, SupportsReadOnly, Protocol

ValueWidget subclass intended for 2D tabular data, with row & column headers.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_bind_change_callback","title":"_mgui_bind_change_callback(callback: Callable[[Any], Any]) -> None abstractmethod","text":"

Bind callback to value change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_bind_column_headers_change_callback","title":"_mgui_bind_column_headers_change_callback(callback: Callable[[Any], None]) -> None abstractmethod","text":"

Bind callback to column headers change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_bind_row_headers_change_callback","title":"_mgui_bind_row_headers_change_callback(callback: Callable[[Any], None]) -> None abstractmethod","text":"

Bind callback to row headers change event.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_cell","title":"_mgui_get_cell(row: int, col: int) -> Any abstractmethod","text":"

Get current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_column_count","title":"_mgui_get_column_count() -> int abstractmethod","text":"

Get the number of columns in the table.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_column_headers","title":"_mgui_get_column_headers() -> tuple abstractmethod","text":"

Get current column headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_row_count","title":"_mgui_get_row_count() -> int abstractmethod","text":"

Get the number of rows in the table.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_get_row_headers","title":"_mgui_get_row_headers() -> tuple abstractmethod","text":"

Get current row headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_remove_column","title":"_mgui_remove_column(column: int) -> None abstractmethod","text":"

Remove column at index column.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_remove_row","title":"_mgui_remove_row(row: int) -> None abstractmethod","text":"

Remove row at index row.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_cell","title":"_mgui_set_cell(row: int, col: int, value: Any) -> None abstractmethod","text":"

Set current value of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_column_count","title":"_mgui_set_column_count(ncols: int) -> None abstractmethod","text":"

Set the number of columns in the table. (Create/delete as needed).

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_column_headers","title":"_mgui_set_column_headers(headers: Sequence) -> None abstractmethod","text":"

Set current column headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_row_count","title":"_mgui_set_row_count(nrows: int) -> None abstractmethod","text":"

Set the number of rows in the table. (Create/delete as needed).

"},{"location":"api/protocols/#magicgui.widgets.protocols.TableWidgetProtocol._mgui_set_row_headers","title":"_mgui_set_row_headers(headers: Sequence) -> None abstractmethod","text":"

Set current row headers of the widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol","title":"magicgui.widgets.protocols.RangedWidgetProtocol","text":"

Bases: ValueWidgetProtocol, Protocol

Value widget that supports numbers within a provided min/max range.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_adaptive_step","title":"_mgui_get_adaptive_step() -> bool abstractmethod","text":"

Get adaptive step status.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_max","title":"_mgui_get_max() -> float abstractmethod","text":"

Get the maximum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_min","title":"_mgui_get_min() -> float abstractmethod","text":"

Get the minimum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_get_step","title":"_mgui_get_step() -> float abstractmethod","text":"

Get the step size.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_adaptive_step","title":"_mgui_set_adaptive_step(value: bool) -> None abstractmethod","text":"

Set adaptive step status.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_max","title":"_mgui_set_max(value: float) -> None abstractmethod","text":"

Set the maximum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_min","title":"_mgui_set_min(value: float) -> None abstractmethod","text":"

Set the minimum possible value.

"},{"location":"api/protocols/#magicgui.widgets.protocols.RangedWidgetProtocol._mgui_set_step","title":"_mgui_set_step(value: float) -> None abstractmethod","text":"

Set the step size.

"},{"location":"api/protocols/#magicgui.widgets.protocols.CategoricalWidgetProtocol","title":"magicgui.widgets.protocols.CategoricalWidgetProtocol","text":"

Bases: ValueWidgetProtocol, SupportsChoices, Protocol

Categorical widget, that has a set of valid choices, and a current value.

It adds no additional methods.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol","title":"magicgui.widgets.protocols.SliderWidgetProtocol","text":"

Bases: RangedWidgetProtocol, SupportsOrientation, Protocol

Protocol for implementing a slider widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol._mgui_get_tracking","title":"_mgui_get_tracking() -> bool","text":"

If tracking is False, changed is only emitted when released.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol._mgui_set_readout_visibility","title":"_mgui_set_readout_visibility(visible: bool) -> None","text":"

Set visibility of readout widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SliderWidgetProtocol._mgui_set_tracking","title":"_mgui_set_tracking(tracking: bool) -> None","text":"

If tracking is False, changed is only emitted when released.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol","title":"magicgui.widgets.protocols.ContainerProtocol","text":"

Bases: WidgetProtocol, SupportsOrientation, Protocol

Widget that can contain other widgets.

This generally manages a backend Layout.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_get_margins","title":"_mgui_get_margins() -> tuple[int, int, int, int] abstractmethod","text":"

Get the margins of the container.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_insert_widget","title":"_mgui_insert_widget(position: int, widget: Widget) -> None abstractmethod","text":"

Insert widget at the given position in the layout.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_remove_widget","title":"_mgui_remove_widget(widget: Widget) -> None abstractmethod","text":"

Remove the specified widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.ContainerProtocol._mgui_set_margins","title":"_mgui_set_margins(margins: tuple[int, int, int, int]) -> None abstractmethod","text":"

Set the margins of the container.

"},{"location":"api/protocols/#magicgui.widgets.protocols.DialogProtocol","title":"magicgui.widgets.protocols.DialogProtocol","text":"

Bases: ContainerProtocol, Protocol

Protocol for modal (blocking) containers.

"},{"location":"api/protocols/#magicgui.widgets.protocols.DialogProtocol._mgui_exec","title":"_mgui_exec() -> None abstractmethod","text":"

Show the dialog and block.

"},{"location":"api/protocols/#magicgui.widgets.protocols.MainWindowProtocol","title":"magicgui.widgets.protocols.MainWindowProtocol","text":"

Bases: ContainerProtocol, Protocol

Application main widget.

"},{"location":"api/protocols/#magicgui.widgets.protocols.MainWindowProtocol._mgui_create_menu_item","title":"_mgui_create_menu_item(menu_name: str, action_name: str, callback: Callable | None = None, shortcut: str | None = None) -> None abstractmethod","text":"

Create a new menu item.

Parameters:

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices","title":"magicgui.widgets.protocols.SupportsChoices","text":"

Bases: Protocol

Widget that has a set of valid choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_del_choice","title":"_mgui_del_choice(choice_name: str) -> None abstractmethod","text":"

Delete the provided choice_name and associated data.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_choice","title":"_mgui_get_choice(choice_name: str) -> Any abstractmethod","text":"

Get data for a single choice.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_choices","title":"_mgui_get_choices() -> tuple[tuple[str, Any], ...] abstractmethod","text":"

Get available choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_count","title":"_mgui_get_count() -> int abstractmethod","text":"

Return number of choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_get_current_choice","title":"_mgui_get_current_choice() -> str abstractmethod","text":"

Return the text of the currently selected choice.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_set_choice","title":"_mgui_set_choice(choice_name: str, data: Any) -> None abstractmethod","text":"

Set data for choice_name, or add a new item if choice_name doesn't exist.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsChoices._mgui_set_choices","title":"_mgui_set_choices(choices: Iterable[tuple[str, Any]]) -> None abstractmethod","text":"

Set available choices.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsOrientation","title":"magicgui.widgets.protocols.SupportsOrientation","text":"

Bases: Protocol

Widget that can be reoriented.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsOrientation._mgui_get_orientation","title":"_mgui_get_orientation() -> str abstractmethod","text":"

Get orientation, return either 'horizontal' or 'vertical'.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsOrientation._mgui_set_orientation","title":"_mgui_set_orientation(value: str) -> None abstractmethod","text":"

Set orientation, value will be 'horizontal' or 'vertical'.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsText","title":"magicgui.widgets.protocols.SupportsText","text":"

Bases: Protocol

Widget that have text (in addition to value)... like buttons.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsText._mgui_get_text","title":"_mgui_get_text() -> str abstractmethod","text":"

Get text.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsText._mgui_set_text","title":"_mgui_set_text(value: str) -> None abstractmethod","text":"

Set text.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsReadOnly","title":"magicgui.widgets.protocols.SupportsReadOnly","text":"

Bases: Protocol

Widget that can be read_only.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsReadOnly._mgui_get_read_only","title":"_mgui_get_read_only() -> bool abstractmethod","text":"

Get read_only status.

"},{"location":"api/protocols/#magicgui.widgets.protocols.SupportsReadOnly._mgui_set_read_only","title":"_mgui_set_read_only(value: bool) -> None abstractmethod","text":"

Set read_only.

"},{"location":"api/protocols/#application-protocol","title":"Application Protocol","text":""},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend","title":"magicgui.widgets.protocols.BaseApplicationBackend","text":"

Bases: ABC

Backend Application object.

Abstract class that provides an interface between backends and Application. Each backend must implement a subclass of BaseApplicationBackend, and implement all of its _mgui_xxx methods.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_get_backend_name","title":"_mgui_get_backend_name() -> str abstractmethod","text":"

Return the name of the backend.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_get_native_app","title":"_mgui_get_native_app() -> Any abstractmethod","text":"

Return the native GUI application instance.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_process_events","title":"_mgui_process_events() -> None abstractmethod","text":"

Process all pending GUI events.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_quit","title":"_mgui_quit() -> None abstractmethod","text":"

Quit the native GUI event loop.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_run","title":"_mgui_run() -> None abstractmethod","text":"

Start the application.

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_start_timer","title":"_mgui_start_timer(interval: int = 0, on_timeout: Callable[[], None] | None = None, single: bool = False) -> None abstractmethod","text":"

Create and start a timer.

Parameters:

"},{"location":"api/protocols/#magicgui.widgets.protocols.BaseApplicationBackend._mgui_stop_timer","title":"_mgui_stop_timer() -> None abstractmethod","text":"

Stop timer. Should check for the existence of the timer.

"},{"location":"api/type_map/","title":"magicgui.type_map","text":"Widget Description get_widget_class Return a Widget subclass for the value/annotation. register_type Register a widget_type to be used for all parameters with type type_. type_registered Context manager that temporarily registers a widget type for a given type_. type2callback Return any callbacks that have been registered for type_."},{"location":"api/type_map/#magicgui.type_map.get_widget_class","title":"magicgui.type_map.get_widget_class(value: Any = Undefined, annotation: Any = Undefined, options: dict | None = None, is_result: bool = False, raise_on_unknown: bool = True) -> tuple[WidgetClass, dict]","text":"

Return a Widget subclass for the value/annotation.

Parameters:

Returns:

"},{"location":"api/type_map/#magicgui.type_map.register_type","title":"magicgui.type_map.register_type(type_: _T | None = None, *, widget_type: WidgetRef | None = None, return_callback: ReturnCallback | None = None, **options: Any) -> _T | Callable[[_T], _T]","text":"

Register a widget_type to be used for all parameters with type type_.

Note: registering a Union (or Optional) type effectively registers all types in the union with the arguments.

Parameters:

Raises:

"},{"location":"api/type_map/#magicgui.type_map.type_registered","title":"magicgui.type_map.type_registered(type_: _T, *, widget_type: WidgetRef | None = None, return_callback: ReturnCallback | None = None, **options: Any) -> Iterator[None]","text":"

Context manager that temporarily registers a widget type for a given type_.

When the context is exited, the previous widget type associations for type_ is restored.

Parameters:

"},{"location":"api/type_map/#magicgui.type_map.type2callback","title":"magicgui.type_map.type2callback(type_: type) -> list[ReturnCallback]","text":"

Return any callbacks that have been registered for type_.

Parameters:

Returns:

"},{"location":"api/widgets/","title":"Widget Index","text":"

Here you will find a list of all the widgets that are available in magicgui. Each widget has a link to its own documentation page, where you can find more information about the widget, including its parameters and events.

Widget Description CheckBox A checkbox with a text label. ComboBox A dropdown menu, allowing selection between multiple choices. Container A Widget to contain other widgets. DateEdit A widget for editing dates. DateTimeEdit A widget for editing dates and times. Dialog A modal container. EmptyWidget A base widget with no value. FileEdit A LineEdit widget with a button that opens a FileDialog. FloatRangeSlider A slider widget to adjust a range defined by two float values within a range. FloatSlider A slider widget to adjust an integer value within a range. FloatSpinBox A widget to edit a float with clickable up/down arrows. FunctionGui Wrapper for a container of widgets representing a callable object. Image A non-editable image display. Label A non-editable text display. LineEdit A one-line text editor. ListEdit A widget to represent a list of values. LiteralEvalLineEdit A one-line text editor that evaluates strings as python literals. LogSlider A slider widget to adjust a numerical value logarithmically within a range. MainFunctionGui Container of widgets as a Main Application Window. MainWindow A Widget to contain other widgets, includes a menu bar. Password A one-line text editor that obscures input. ProgressBar A progress bar widget. PushButton A clickable command button. QuantityEdit A combined LineEdit and ComboBox to edit a pint.Quantity. RadioButton A radio button with a text label. RadioButtons An exclusive group of radio buttons, providing a choice from multiple choices. RangeEdit A widget to represent a python range object, with start/stop/step. RangeSlider A slider widget to adjust a range between two integer values within a range. Select A list of options, allowing selection between multiple choices. SliceEdit A widget to represent slice objects, with start/stop/step. Slider A slider widget to adjust an integer value within a range. SpinBox A widget to edit an integer with clickable up/down arrows. Table A widget to represent columnar or 2D data with headers. TextEdit A widget to edit and display both plain and rich text. TimeEdit A widget for editing times. TupleEdit A widget to represent a tuple of values."},{"location":"api/widgets/CheckBox/","title":"CheckBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/CheckBox/#signals","title":"Signals","text":""},{"location":"api/widgets/CheckBox/#magicgui.widgets.CheckBox","title":"CheckBox","text":"

Bases: ButtonWidget

A checkbox with a text label.

Parameters:

"},{"location":"api/widgets/ComboBox/","title":"ComboBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/ComboBox/#signals","title":"Signals","text":""},{"location":"api/widgets/ComboBox/#magicgui.widgets.ComboBox","title":"ComboBox","text":"

Bases: CategoricalWidget

A dropdown menu, allowing selection between multiple choices.

Parameters:

"},{"location":"api/widgets/Container/","title":"Container","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Container/#signals","title":"Signals","text":""},{"location":"api/widgets/Container/#magicgui.widgets.Container","title":"Container","text":"

Bases: ContainerWidget[WidgetVar]

A Widget to contain other widgets.

Note that `Container` implements the\n[`typing.MutableSequence`][typing.MutableSequence]\ninterface, so you can use it like a list to add and remove widgets.\n

Parameters:

"},{"location":"api/widgets/DateEdit/","title":"DateEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/DateEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/DateEdit/#magicgui.widgets.DateEdit","title":"DateEdit","text":"

Bases: ValueWidget[date]

A widget for editing dates.

Parameters:

"},{"location":"api/widgets/DateTimeEdit/","title":"DateTimeEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/DateTimeEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/DateTimeEdit/#magicgui.widgets.DateTimeEdit","title":"DateTimeEdit","text":"

Bases: ValueWidget[datetime]

A widget for editing dates and times.

Parameters:

"},{"location":"api/widgets/Dialog/","title":"Dialog","text":"

Available in backends: qt

"},{"location":"api/widgets/Dialog/#signals","title":"Signals","text":""},{"location":"api/widgets/Dialog/#magicgui.widgets.Dialog","title":"Dialog","text":"

Bases: DialogWidget

A modal container.

Parameters:

"},{"location":"api/widgets/EmptyWidget/","title":"EmptyWidget","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/EmptyWidget/#signals","title":"Signals","text":""},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget","title":"EmptyWidget","text":"

Bases: ValueWidget

A base widget with no value.

This widget is primarily here to serve as a \"hidden widget\" to which a value or\ncallback can be bound.\n

Parameters:

"},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget.value","title":"value: Any property writable","text":"

Look for a bound value, otherwise fallback to get_value.

"},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget.__repr__","title":"__repr__() -> str","text":"

Return string repr (avoid looking for value).

"},{"location":"api/widgets/EmptyWidget/#magicgui.widgets.EmptyWidget.get_value","title":"get_value() -> Any","text":"

Return value if one has been manually set... otherwise return Param.empty.

"},{"location":"api/widgets/FileEdit/","title":"FileEdit","text":"

Available in backends:

"},{"location":"api/widgets/FileEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit","title":"FileEdit","text":"

Bases: Container

A LineEdit widget with a button that opens a FileDialog.

Parameters:

"},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit.mode","title":"mode: FileDialogMode property writable","text":"

Mode for the FileDialog.

"},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit.value","title":"value: tuple[Path, ...] | Path | None property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/FileEdit/#magicgui.widgets.FileEdit.__repr__","title":"__repr__() -> str","text":"

Return string representation.

"},{"location":"api/widgets/FloatRangeSlider/","title":"FloatRangeSlider","text":"

Available in backends: qt

"},{"location":"api/widgets/FloatRangeSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/FloatRangeSlider/#magicgui.widgets.FloatRangeSlider","title":"FloatRangeSlider","text":"

Bases: MultiValuedSliderWidget

A slider widget to adjust a range defined by two float values within a range.

Parameters:

"},{"location":"api/widgets/FloatSlider/","title":"FloatSlider","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/FloatSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/FloatSlider/#magicgui.widgets.FloatSlider","title":"FloatSlider","text":"

Bases: SliderWidget[float]

A slider widget to adjust an integer value within a range.

Parameters:

"},{"location":"api/widgets/FloatSpinBox/","title":"FloatSpinBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/FloatSpinBox/#signals","title":"Signals","text":""},{"location":"api/widgets/FloatSpinBox/#magicgui.widgets.FloatSpinBox","title":"FloatSpinBox","text":"

Bases: RangedWidget[float]

A widget to edit a float with clickable up/down arrows.

Parameters:

"},{"location":"api/widgets/FunctionGui/","title":"FunctionGui","text":"

Available in backends:

"},{"location":"api/widgets/FunctionGui/#signals","title":"Signals","text":""},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui","title":"FunctionGui","text":"

Bases: Container, Generic[_P, _R]

Wrapper for a container of widgets representing a callable object.

Parameters:

Raises:

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__signature__","title":"__signature__: MagicSignature property","text":"

Return a MagicSignature object representing the current state of the gui.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.call_button","title":"call_button: PushButton | None property","text":"

Return the call button.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.call_count","title":"call_count: int property","text":"

Return the number of times the function has been called.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.result_name","title":"result_name: str property writable","text":"

Return a name that can be used for the result of this magicfunction.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.return_annotation","title":"return_annotation: Any property","text":"

Return annotation for inspect.Signature conversion.

ForwardRefs will be resolve when setting the annotation.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__call__","title":"__call__(*args: _P.args, **kwargs: _P.kwargs) -> _R","text":"

Call the original function with the current parameter values from the Gui.

You may pass a update_widget=True keyword argument to update the widget values to match the current parameter values before calling the function.

It is also possible to override the current parameter values from the GUI by providing args/kwargs to the function call. Only those provided will override the ones from the gui. A called signal will also be emitted with the results.

Returns:

Examples:

gui = FunctionGui(func, show=True)\n\n# then change parameters in the gui, or by setting:  gui.param.value = something\n\ngui()  # calls the original function with the current parameters\n
"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__get__","title":"__get__(obj: object, objtype: type | None = None) -> FunctionGui","text":"

Provide descriptor protocol.

This allows the @magicgui decorator to work on a function as well as a method. If a method on a class is decorated with @magicgui, then accessing the attribute on an instance of that class will return a version of the FunctionGui in which the first argument of the function is bound to the instance. (Just like what you'd expect with the @property decorator.)

Returns:

Examples:

>>> class MyClass:\n...     @magicgui\n...     def my_method(self, x=1):\n...         print(locals())\n...\n>>> c = MyClass()\n>>> c.my_method  # the FunctionGui that can be used as a widget\n\n# calling it works as usual, with `c` provided as `self`\n>>> c.my_method(x=34)\n{'self': <__main__.MyClass object at 0x7fb610e455e0>, 'x': 34}\n
"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__init__","title":"__init__(function: Callable[_P, _R], call_button: bool | str | None = None, layout: str = 'vertical', scrollable: bool = False, labels: bool = True, tooltips: bool = True, app: AppRef | None = None, visible: bool | None = None, auto_call: bool = False, result_widget: bool = False, param_options: dict[str, dict] | None = None, name: str | None = None, persist: bool = False, raise_on_unknown: bool = False, **kwargs: Any)","text":""},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__repr__","title":"__repr__() -> str","text":"

Return string representation of instance.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.__set__","title":"__set__(obj: Any, value: Any) -> NoReturn","text":"

Prevent setting a magicgui attribute.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.copy","title":"copy() -> FunctionGui","text":"

Return a copy of this FunctionGui.

"},{"location":"api/widgets/FunctionGui/#magicgui.widgets.FunctionGui.reset_call_count","title":"reset_call_count() -> None","text":"

Reset the call count to 0.

"},{"location":"api/widgets/Image/","title":"Image","text":"

Available in backends: qt

"},{"location":"api/widgets/Image/#signals","title":"Signals","text":""},{"location":"api/widgets/Image/#magicgui.widgets.Image","title":"Image","text":"

Bases: ValueWidget

A non-editable image display.

Parameters:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.image_data","title":"image_data: np.ndarray | None property","text":"

Return image data.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.image_rgba","title":"image_rgba: np.ndarray | None property","text":"

Return rendered numpy array.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.value","title":"value property writable","text":"

Return current image array.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.__repr__","title":"__repr__() -> str","text":"

Return representation of widget of instance.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.get_clim","title":"get_clim() -> tuple[float | None, float | None]","text":"

Get contrast limits (for monochromatic images).

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.scale_widget_to_image_size","title":"scale_widget_to_image_size()","text":"

Set the size of the widget to the size of the image.

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_clim","title":"set_clim(vmin: float | None = None, vmax: float | None = None)","text":"

Set contrast limits (for monochromatic images).

Parameters:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_cmap","title":"set_cmap(cmap: str | Colormap | matplotlib.colors.Colormap)","text":"

Set colormap (for monochromatic images).

Parameters:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_data","title":"set_data(val: str | Path | np.ndarray | PIL.Image.Image, cmap: str | Colormap | matplotlib.colors.Colormap | None = None, norm: _mpl_image.Normalize | matplotlib.colors.Normalize | None = None, vmin: float | None = None, vmax: float | None = None, width: int | Literal['auto'] | None = None, height: int | Literal['auto'] | None = None, format: str | None = None)","text":"

Set image data with various optional display parameters.

Parameters:

Raises:

"},{"location":"api/widgets/Image/#magicgui.widgets.Image.set_norm","title":"set_norm(norm: Normalize | matplotlib.colors.Normalize)","text":"

Set normalization method.

Parameters:

"},{"location":"api/widgets/Label/","title":"Label","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Label/#signals","title":"Signals","text":""},{"location":"api/widgets/Label/#magicgui.widgets.Label","title":"Label","text":"

Bases: ValueWidget[str]

A non-editable text display.

Parameters:

"},{"location":"api/widgets/LineEdit/","title":"LineEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/LineEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/LineEdit/#magicgui.widgets.LineEdit","title":"LineEdit","text":"

Bases: ValueWidget[str]

A one-line text editor.

Parameters:

"},{"location":"api/widgets/ListEdit/","title":"ListEdit","text":"

Available in backends:

"},{"location":"api/widgets/ListEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit","title":"ListEdit","text":"

Bases: Container[ValueWidget[_V]]

A widget to represent a list of values.

A ListEdit container can create a list with multiple objects of same type. It\nwill contain many child widgets and their value is represented as a Python list\nobject. If a list is given as the initial value, types of child widgets are\ndetermined from the contents. Number of contents can be adjusted with +/-\nbuttons.\n

Parameters:

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation. For ListEdit, annotation will be like 'list[str]'.

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.data","title":"data: ListDataView[_V] property writable","text":"

Return a data view of current value.

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.value","title":"value: list[_V] property writable","text":"

Return current value as a list object.

"},{"location":"api/widgets/ListEdit/#magicgui.widgets.ListEdit.__delitem__","title":"__delitem__(key: int | slice) -> None","text":"

Delete child widget(s).

"},{"location":"api/widgets/LiteralEvalLineEdit/","title":"LiteralEvalLineEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/LiteralEvalLineEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/LiteralEvalLineEdit/#magicgui.widgets.LiteralEvalLineEdit","title":"LiteralEvalLineEdit","text":"

Bases: ValueWidget[str]

A one-line text editor that evaluates strings as python literals.

Parameters:

"},{"location":"api/widgets/LogSlider/","title":"LogSlider","text":"

Available in backends:

"},{"location":"api/widgets/LogSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/LogSlider/#magicgui.widgets.LogSlider","title":"LogSlider","text":"

Bases: TransformedRangedWidget

A slider widget to adjust a numerical value logarithmically within a range.

Parameters:

"},{"location":"api/widgets/LogSlider/#magicgui.widgets.LogSlider.base","title":"base: float property writable","text":"

Return base used for the log.

"},{"location":"api/widgets/LogSlider/#magicgui.widgets.LogSlider.tracking","title":"tracking: bool property writable","text":"

Return whether slider tracking is enabled.

If tracking is enabled (the default), the slider emits the changed() signal while the slider is being dragged. If tracking is disabled, the slider emits the changed() signal only when the user releases the slider.

"},{"location":"api/widgets/MainFunctionGui/","title":"MainFunctionGui","text":"

Available in backends:

"},{"location":"api/widgets/MainFunctionGui/#signals","title":"Signals","text":""},{"location":"api/widgets/MainFunctionGui/#magicgui.widgets.MainFunctionGui","title":"MainFunctionGui","text":"

Bases: FunctionGui[_P, _R], MainWindow

Container of widgets as a Main Application Window.

"},{"location":"api/widgets/MainWindow/","title":"MainWindow","text":"

Available in backends: qt

"},{"location":"api/widgets/MainWindow/#signals","title":"Signals","text":""},{"location":"api/widgets/MainWindow/#magicgui.widgets.MainWindow","title":"MainWindow","text":"

Bases: MainWindowWidget

A Widget to contain other widgets, includes a menu bar.

Parameters:

"},{"location":"api/widgets/Password/","title":"Password","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Password/#signals","title":"Signals","text":""},{"location":"api/widgets/Password/#magicgui.widgets.Password","title":"Password","text":"

Bases: ValueWidget[str]

A one-line text editor that obscures input.

Parameters:

"},{"location":"api/widgets/ProgressBar/","title":"ProgressBar","text":"

Available in backends: qt

"},{"location":"api/widgets/ProgressBar/#signals","title":"Signals","text":""},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar","title":"ProgressBar","text":"

Bases: SliderWidget[float]

A progress bar widget.

Parameters:

"},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar.step","title":"step: float property writable","text":"

Step size for widget values.

"},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar.decrement","title":"decrement(val: float | None = None) -> None","text":"

Decrease current value by step size, or provided value.

"},{"location":"api/widgets/ProgressBar/#magicgui.widgets.ProgressBar.increment","title":"increment(val: float | None = None) -> None","text":"

Increase current value by step size, or provided value.

"},{"location":"api/widgets/PushButton/","title":"PushButton","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/PushButton/#signals","title":"Signals","text":""},{"location":"api/widgets/PushButton/#magicgui.widgets.PushButton","title":"PushButton","text":"

Bases: ButtonWidget

A clickable command button.

Parameters:

"},{"location":"api/widgets/QuantityEdit/","title":"QuantityEdit","text":"

Available in backends: qt

"},{"location":"api/widgets/QuantityEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/QuantityEdit/#magicgui.widgets.QuantityEdit","title":"QuantityEdit","text":"

Bases: ValueWidget

A combined LineEdit and ComboBox to edit a pint.Quantity.

Parameters:

"},{"location":"api/widgets/RadioButton/","title":"RadioButton","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/RadioButton/#signals","title":"Signals","text":""},{"location":"api/widgets/RadioButton/#magicgui.widgets.RadioButton","title":"RadioButton","text":"

Bases: ButtonWidget

A radio button with a text label.

Parameters:

"},{"location":"api/widgets/RadioButtons/","title":"RadioButtons","text":"

Available in backends: qt

"},{"location":"api/widgets/RadioButtons/#signals","title":"Signals","text":""},{"location":"api/widgets/RadioButtons/#magicgui.widgets.RadioButtons","title":"RadioButtons","text":"

Bases: CategoricalWidget, _OrientationMixin

An exclusive group of radio buttons, providing a choice from multiple choices.

Parameters:

"},{"location":"api/widgets/RangeEdit/","title":"RangeEdit","text":"

Available in backends:

"},{"location":"api/widgets/RangeEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/RangeEdit/#magicgui.widgets.RangeEdit","title":"RangeEdit","text":"

Bases: Container[SpinBox]

A widget to represent a python range object, with start/stop/step.

A range object produces a sequence of integers from start (inclusive)\nto stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.\nstart defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.\nThese are exactly the valid indices for a list of 4 elements.\nWhen step is given, it specifies the increment (or decrement).\n

Parameters:

"},{"location":"api/widgets/RangeEdit/#magicgui.widgets.RangeEdit.value","title":"value: range property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/RangeEdit/#magicgui.widgets.RangeEdit.__repr__","title":"__repr__() -> str","text":"

Return string representation.

"},{"location":"api/widgets/RangeSlider/","title":"RangeSlider","text":"

Available in backends: qt

"},{"location":"api/widgets/RangeSlider/#signals","title":"Signals","text":""},{"location":"api/widgets/RangeSlider/#magicgui.widgets.RangeSlider","title":"RangeSlider","text":"

Bases: MultiValuedSliderWidget

A slider widget to adjust a range between two integer values within a range.

Parameters:

"},{"location":"api/widgets/Select/","title":"Select","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Select/#signals","title":"Signals","text":""},{"location":"api/widgets/Select/#magicgui.widgets.Select","title":"Select","text":"

Bases: CategoricalWidget

A list of options, allowing selection between multiple choices.

Parameters:

"},{"location":"api/widgets/SliceEdit/","title":"SliceEdit","text":"

Available in backends:

"},{"location":"api/widgets/SliceEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/SliceEdit/#magicgui.widgets.SliceEdit","title":"SliceEdit","text":"

Bases: RangeEdit

A widget to represent slice objects, with start/stop/step.

slice(stop) slice(start, stop[, step])

Slice objects may be used for extended slicing (e.g. a[0:10:2])

"},{"location":"api/widgets/SliceEdit/#magicgui.widgets.SliceEdit.value","title":"value: slice property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/Slider/","title":"Slider","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/Slider/#signals","title":"Signals","text":""},{"location":"api/widgets/Slider/#magicgui.widgets.Slider","title":"Slider","text":"

Bases: SliderWidget[int]

A slider widget to adjust an integer value within a range.

Parameters:

"},{"location":"api/widgets/SpinBox/","title":"SpinBox","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/SpinBox/#signals","title":"Signals","text":""},{"location":"api/widgets/SpinBox/#magicgui.widgets.SpinBox","title":"SpinBox","text":"

Bases: RangedWidget[int]

A widget to edit an integer with clickable up/down arrows.

Parameters:

"},{"location":"api/widgets/Table/","title":"Table","text":"

Available in backends: qt

"},{"location":"api/widgets/Table/#signals","title":"Signals","text":""},{"location":"api/widgets/Table/#magicgui.widgets.Table","title":"Table","text":"

Bases: ValueWidget, _ReadOnlyMixin, MutableMapping[TblKey, list]

A widget to represent columnar or 2D data with headers.

Tables behave like plain dicts, where the keys are column headers and the (list-like) values are column data.

Parameters:

index : Collection, optional A sized iterable container of row headers. By default, row headers will be tuple(range(len(data))). Values provided here override any implied in value. columns : Collection, optional A sized iterable container of column headers. By default, column headers will be tuple(range(len(data[0]))). Values provided here override any implied in value. **kwargs Additional kwargs will be passed to the magicgui.widgets.Widget constructor.

Attributes:

Methods:

"},{"location":"api/widgets/Table/#magicgui.widgets.Table--events","title":"Events","text":"

changed Emitted whenever a cell in the table changes. The value will have a dict of information regarding the cell that changed: {'data': x, 'row': int, 'column': int, 'column_header': str, 'row_header': str} CURRENTLY: only emitted on changes in the GUI. not programmatic changes.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.column_headers","title":"column_headers: tuple property writable","text":"

Return column headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.data","title":"data: DataView property writable","text":"

Return DataView object for this table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.row_headers","title":"row_headers: tuple property writable","text":"

Return row headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.shape","title":"shape: tuple[int, int] property","text":"

Return shape of table widget (rows, cols).

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.size","title":"size: int property","text":"

Return shape of table widget (rows, cols).

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.value","title":"value: dict[TblKey, Collection] property writable","text":"

Return dict with current data, index, and columns of the widget.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__delitem__","title":"__delitem__(key: TblKey) -> None","text":"

Delete a column from the table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__getitem__","title":"__getitem__(key: TblKey) -> list","text":"

Get a column from the table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__hash__","title":"__hash__() -> int","text":"

Make table hashable.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__iter__","title":"__iter__() -> Iterator","text":"

Yield column headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__len__","title":"__len__() -> int","text":"

Return number of columns.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__new__","title":"__new__(value: TableData | None = None, *, index: Collection | None = None, columns: Collection | None = None, **kwargs: Any) -> Table","text":"

Just for the signature.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__repr__","title":"__repr__() -> str","text":"

Return string repr.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.__setitem__","title":"__setitem__(key: TblKey, v: Collection) -> None","text":"

Set a column in the table. If k doesn't exist, make a new column.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.clear","title":"clear() -> None","text":"

Clear the table.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.items","title":"items(axis: str = 'column') -> TableItemsView[TblKey, list]","text":"

Return a set-like object providing a view on this table's items.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.keys","title":"keys(axis: str = 'column') -> HeadersView[TblKey]","text":"

Return a set-like object providing a view on this table's headers.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.to_dataframe","title":"to_dataframe() -> pandas.DataFrame","text":"

Convert TableData to dataframe.

"},{"location":"api/widgets/Table/#magicgui.widgets.Table.to_dict","title":"to_dict(orient: str = 'dict') -> list | dict","text":"

Convert the Table to a dictionary.

The type of the key-value pairs can be customized with the parameters (see below).

Parameters:

"},{"location":"api/widgets/TextEdit/","title":"TextEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/TextEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/TextEdit/#magicgui.widgets.TextEdit","title":"TextEdit","text":"

Bases: ValueWidget[str], _ReadOnlyMixin

A widget to edit and display both plain and rich text.

Parameters:

"},{"location":"api/widgets/TimeEdit/","title":"TimeEdit","text":"

Available in backends: qt, ipynb

"},{"location":"api/widgets/TimeEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/TimeEdit/#magicgui.widgets.TimeEdit","title":"TimeEdit","text":"

Bases: ValueWidget[TV]

A widget for editing times.

Parameters:

"},{"location":"api/widgets/TupleEdit/","title":"TupleEdit","text":"

Available in backends:

"},{"location":"api/widgets/TupleEdit/#signals","title":"Signals","text":""},{"location":"api/widgets/TupleEdit/#magicgui.widgets.TupleEdit","title":"TupleEdit","text":"

Bases: Container[ValueWidget]

A widget to represent a tuple of values.

A TupleEdit container has several child widgets of different type. Their value is\nrepresented as a Python tuple object. If a tuple is given as the initial value,\ntypes of child widgets are determined one by one. Unlike ListEdit, number of\ncontents is not editable.\n

Parameters:

"},{"location":"api/widgets/TupleEdit/#magicgui.widgets.TupleEdit.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation. For TupleEdit, annotation will be like 'tuple[str, int]'.

"},{"location":"api/widgets/TupleEdit/#magicgui.widgets.TupleEdit.value","title":"value: tuple property writable","text":"

Return current value as a tuple.

"},{"location":"api/widgets/bases/","title":"magicgui.widgets.bases","text":"

The magicgui.widgets.bases module contains the base classes for all widgets.

While most users will never instantiate these classes directly, the methods and properties of these classes are inherited by all widgets, and define the common API for all widgets. Therefore, it is worth being aware of the type of widget you are working with.

"},{"location":"api/widgets/bases/#summary","title":"Summary","text":"Widget Description Widget Basic Widget, wrapping a class that implements WidgetProtocol. ButtonWidget Widget with a value, Wraps a widget implementing the ButtonWidgetProtocol. CategoricalWidget Widget with a value and choices. Wraps CategoricalWidgetProtocol. ContainerWidget Widget that can contain other widgets. DialogWidget Modal Container. MainWindowWidget Top level Application widget that can contain other widgets. RangedWidget Widget with a constrained value. Wraps RangedWidgetProtocol. SliderWidget Widget with a constrained value and orientation. Wraps SliderWidgetProtocol. ValueWidget Widget with a value, Wraps ValueWidgetProtocol."},{"location":"api/widgets/bases/#class-hierarchy","title":"Class Hierarchy","text":"

In visual form, the widget class hierarchy looks like this:

classDiagram\n    Widget <|-- ValueWidget\n    Widget <|-- ContainerWidget\n    BackendWidget ..|> WidgetProtocol : implements a\n    ValueWidget <|-- RangedWidget\n    ValueWidget <|-- ButtonWidget\n    ValueWidget <|-- CategoricalWidget\n    RangedWidget <|-- SliderWidget\n    Widget --* WidgetProtocol : controls a\n    <<Interface>> WidgetProtocol\n    class WidgetProtocol {\n        _mgui_get_X()\n        _mgui_set_X()\n    }\n    class Widget{\n        name: str\n        annotation: Any\n        label: str\n        tooltip: str\n        visible: bool\n        enabled: bool\n        native: Any\n        height: int\n        width: int\n        hide()\n        show()\n        close()\n        render()\n    }\n    class ValueWidget{\n        value: Any\n        changed: SignalInstance\n        bind(value, call) Any\n        unbind()\n    }\n    class RangedWidget{\n        value: float | tuple\n        min: float\n        max: float\n        step: float\n        adaptive_step: bool\n        range: tuple[float, float]\n    }\n    class SliderWidget{\n        orientation: str\n    }\n    class ButtonWidget{\n        value: bool\n        clicked: SignalInstance\n        text: str\n    }\n    class CategoricalWidget{\n        choices: List[Any]\n    }\n    class ContainerWidget{\n        widgets: List[Widget]\n        labels: bool\n        layout: str\n        margins: tuple[int, int, int, int]\n        reset_choices()\n        asdict() Dict[str, Any]\n        update(mapping)\n    }\n\n    click Widget href \"#magicgui.widgets.bases.Widget\"\n    click ValueWidget href \"#magicgui.widgets.bases.ValueWidget\"\n    click RangedWidget href \"#magicgui.widgets.bases.RangedWidget\"\n    click SliderWidget href \"#magicgui.widgets.bases.SliderWidget\"\n    click ButtonWidget href \"#magicgui.widgets.bases.ButtonWidget\"\n    click CategoricalWidget href \"#magicgui.widgets.bases.CategoricalWidget\"\n    click ContainerWidget href \"#magicgui.widgets.bases.ContainerWidget\"\n
"},{"location":"api/widgets/bases/#base-widget-classes","title":"Base Widget Classes","text":""},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget","title":"magicgui.widgets.bases.Widget","text":"

Basic Widget, wrapping a class that implements WidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.enabled","title":"enabled: bool property writable","text":"

Whether widget is enabled (editable).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.height","title":"height: int property writable","text":"

Return the current height of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.label","title":"label: str property writable","text":"

Return a label to use for this widget when present in Containers.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.max_height","title":"max_height: int property writable","text":"

Get the maximum height of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.max_width","title":"max_width: int property writable","text":"

Get the maximum width of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.min_height","title":"min_height: int property writable","text":"

Get the minimum height of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.min_width","title":"min_width: int property writable","text":"

Get the minimum width of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.native","title":"native: Any property","text":"

Return native backend widget.

Note this is the widget that contains the layout, and not any parent widgets of this (e.g. a parent widget that is used to enable scroll bars)

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.param_kind","title":"param_kind: inspect._ParameterKind property writable","text":"

Return :attr:inspect.Parameter.kind represented by this widget.

Used in building signatures from multiple widgets, by default :attr:~inspect.Parameter.POSITIONAL_OR_KEYWORD

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.parent","title":"parent: Widget property writable","text":"

Return the parent widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.root_native_widget","title":"root_native_widget: Any property","text":"

Return the root native backend widget.

This can be different from the .native widget if the layout is a child of some other widget, e.g. a widget used to enable scroll bars.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.tooltip","title":"tooltip: str | None property writable","text":"

Get the tooltip for this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.visible","title":"visible: bool property writable","text":"

Return whether widget is visible.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.widget_type","title":"widget_type: str property","text":"

Return type of widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.width","title":"width: int property writable","text":"

Return the current width of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.__repr__","title":"__repr__() -> str","text":"

Return representation of widget of instance.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.close","title":"close() -> None","text":"

Close widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.hide","title":"hide() -> None","text":"

Hide widget.

alias for widget.visible = False

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.render","title":"render() -> np.ndarray","text":"

Return an RGBA (MxNx4) numpy array bitmap of the rendered widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.show","title":"show(run: bool = False) -> Widget","text":"

Show widget.

alias for widget.visible = True

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.Widget.shown","title":"shown() -> Iterator[Application]","text":"

Context manager to show the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget","title":"magicgui.widgets.bases.ButtonWidget","text":"

Bases: ValueWidget[bool]

Widget with a value, Wraps a widget implementing the ButtonWidgetProtocol.

see ButtonWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget.clicked","title":"clicked: SignalInstance property","text":"

Alias for changed event.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ButtonWidget.text","title":"text: str property writable","text":"

Text of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget","title":"magicgui.widgets.bases.CategoricalWidget","text":"

Bases: ValueWidget[T]

Widget with a value and choices. Wraps CategoricalWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.choices","title":"choices: tuple[T | None, ...] property writable","text":"

Available value choices for this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.current_choice","title":"current_choice: str property","text":"

Return the text of the currently selected choice.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.value","title":"value: T property writable","text":"

Return current value of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.__len__","title":"__len__() -> int","text":"

Return the number of choices.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.del_choice","title":"del_choice(choice_name: str) -> None","text":"

Delete the provided choice_name and associated data.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.get_choice","title":"get_choice(choice_name: str) -> T","text":"

Get data for the provided choice_name.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.reset_choices","title":"reset_choices(*_: Any) -> None","text":"

Reset choices to the default state.

If self._default_choices is a callable, this may NOT be the exact same set of choices as when the widget was instantiated, if the callable relies on external state.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.CategoricalWidget.set_choice","title":"set_choice(choice_name: str, data: Any | None = None) -> None","text":"

Set data for the provided choice_name.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget","title":"magicgui.widgets.bases.ContainerWidget","text":"

Bases: Widget, _OrientationMixin, MutableSequence[WidgetVar]

Widget that can contain other widgets.

Wraps a widget that implements ContainerProtocol.

A ContainerWidget behaves like a python list of Widget objects. Subwidgets can be accessed using integer or slice-based indexing (container[0]), as well as by widget name (container.<widget_name>). Widgets can be added with append or insert, and removed with del or pop, etc...

There is a tight connection between a ContainerWidget and an inspect.Signature object, just as there is a tight connection between individual Widgetobjects an an :class:inspect.Parameter object. The signature representation of a ContainerWidget (with the current settings as default values) is accessible with the :meth:~ContainerWidget.__signature__ method (or by using :func:inspect.signature from the standard library)

For a ContainerWidget subclass that is tightly coupled to a specific function signature (as in the \"classic\" magicgui decorator), see magicgui.widgets.FunctionGui.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__signature__","title":"__signature__: MagicSignature property","text":"

Return a MagicSignature object representing the current state of the gui.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.labels","title":"labels: bool property writable","text":"

Whether widgets are presented with labels.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.layout","title":"layout: str property writable","text":"

Return the layout of the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.margins","title":"margins: tuple[int, int, int, int] property writable","text":"

Return margin between the content and edges of the container.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__delattr__","title":"__delattr__(name: str) -> None","text":"

Delete a widget by name.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__delitem__","title":"__delitem__(key: int | slice) -> None","text":"

Delete a widget by integer or slice index.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__dir__","title":"__dir__() -> list[str]","text":"

Add subwidget names to the dir() call for this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__getattr__","title":"__getattr__(name: str) -> WidgetVar","text":"

Return attribute name. Will return a widget if present.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__getitem__","title":"__getitem__(key: int | str | slice) -> WidgetVar | MutableSequence[WidgetVar]","text":"

Get item by integer, str, or slice.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__len__","title":"__len__() -> int","text":"

Return the count of widgets.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__repr__","title":"__repr__() -> str","text":"

Return a repr.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__setattr__","title":"__setattr__(name: str, value: Any) -> None","text":"

Set attribute name. Prevents changing widget if present, (use del).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.__setitem__","title":"__setitem__(key: Any, value: Any) -> NoReturn","text":"

Prevent assignment by index.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.asdict","title":"asdict() -> dict[str, Any]","text":"

Return state of widget as dict.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.from_callable","title":"from_callable(obj: Callable, gui_options: dict | None = None, **kwargs: Unpack[ContainerKwargs]) -> Container classmethod","text":"

Create a Container widget from a callable object.

In most cases, it will be preferable to create a FunctionGui instead.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.from_signature","title":"from_signature(sig: inspect.Signature, **kwargs: Unpack[ContainerKwargs]) -> Container classmethod","text":"

Create a Container widget from an inspect.Signature object.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.index","title":"index(value: Any, start: int = 0, stop: int = 9223372036854775807) -> int","text":"

Return index of a specific widget instance (or widget name).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.insert","title":"insert(key: int, widget: WidgetVar) -> None","text":"

Insert widget at key.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.remove","title":"remove(value: Widget | str) -> None","text":"

Remove a widget instance (may also be string name of widget).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.reset_choices","title":"reset_choices(*_: Any) -> None","text":"

Reset choices for all Categorical subWidgets to the default state.

If widget._default_choices is a callable, this may NOT be the exact same set of choices as when the widget was instantiated, if the callable relies on external state.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ContainerWidget.update","title":"update(mapping: Mapping | Iterable[tuple[str, Any]] | None = None, **kwargs: Any) -> None","text":"

Update the parameters in the widget from a mapping, iterable, or kwargs.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.DialogWidget","title":"magicgui.widgets.bases.DialogWidget","text":"

Bases: ContainerWidget

Modal Container.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.DialogWidget.exec","title":"exec() -> bool","text":"

Show the dialog, and block.

Return True if the dialog was accepted, False if rejected.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.MainWindowWidget","title":"magicgui.widgets.bases.MainWindowWidget","text":"

Bases: ContainerWidget

Top level Application widget that can contain other widgets.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.MainWindowWidget.create_menu_item","title":"create_menu_item(menu_name: str, item_name: str, callback: Callable | None = None, shortcut: str | None = None) -> None","text":"

Create a menu item item_name under menu menu_name.

menu_name will be created if it does not already exist.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget","title":"magicgui.widgets.bases.RangedWidget","text":"

Bases: ValueWidget[T]

Widget with a constrained value. Wraps RangedWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.adaptive_step","title":"adaptive_step: bool property writable","text":"

Whether the step size is adaptive.

Adaptive decimal step means that the step size will continuously be adjusted to one power of ten below the current value. So when the value is 1100, the step is set to 100, so stepping up once increases it to 1200. For 1200 stepping up takes it to 1300. For negative values, stepping down from -1100 goes to -1200.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.max","title":"max: float property writable","text":"

Maximum allowable value for the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.min","title":"min: float property writable","text":"

Minimum allowable value for the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.range","title":"range: tuple[float, float] property writable","text":"

Range of allowable values for the widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.step","title":"step: float | None property writable","text":"

Step size for widget values (None if adaptive step is turned on).

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.RangedWidget.value","title":"value(value: T) -> None","text":"

Set widget value, will raise Value error if not within min/max.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget","title":"magicgui.widgets.bases.SliderWidget","text":"

Bases: RangedWidget[T], _OrientationMixin

Widget with a constrained value and orientation. Wraps SliderWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget.options","title":"options: dict property","text":"

Return options currently being used in this widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget.readout","title":"readout: bool property writable","text":"

Get visibility state of readout widget.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.SliderWidget.tracking","title":"tracking: bool property writable","text":"

Return whether slider tracking is enabled.

If tracking is enabled (the default), the slider emits the changed() signal while the slider is being dragged. If tracking is disabled, the slider emits the changed() signal only when the user releases the slider.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget","title":"magicgui.widgets.bases.ValueWidget","text":"

Bases: Widget, Generic[T]

Widget with a value, Wraps ValueWidgetProtocol.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.annotation","title":"annotation: Any property writable","text":"

Return type annotation for the parameter represented by the widget.

ForwardRefs will be resolve when setting the annotation. If the widget is nullable (had a type annototation of Optional[Type]), annotation will return the first argument in the Optional clause.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.value","title":"value: T property writable","text":"

Return current value of the widget. This may be interpreted by backends.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.__repr__","title":"__repr__() -> str","text":"

Return representation of widget of instance.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.bind","title":"bind(value: T | Callable[[ValueWidget], T], call: bool = True) -> None","text":"

Binds value to self.value.

If a value is bound to this widget, then whenever widget.value is accessed, the value provided here will be returned. value can be a callable, in which case value(self) will be returned (i.e. your callback must accept a single parameter, which is this widget instance.).

If you provide a callable and you don't want it to be called (but rather just returned as a callable object, then use call=False when binding your value.

Note: if you need to access the \"original\" widget.value within your callback, please use widget.get_value() instead of the widget.value property, in order to avoid a RuntimeError.

Parameters:

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.get_value","title":"get_value() -> T","text":"

Callable version of self.value.

The main API is to use self.value, however, this is here in order to provide an escape hatch if trying to access the widget's value inside of a callback bound to self._bound_value.

"},{"location":"api/widgets/bases/#magicgui.widgets.bases.ValueWidget.unbind","title":"unbind() -> None","text":"

Unbinds any bound values. (see ValueWidget.bind).

"},{"location":"api/widgets/create_widget/","title":"magicgui.widgets.create_widget","text":""},{"location":"api/widgets/create_widget/#magicgui.widgets.create_widget","title":"magicgui.widgets.create_widget(value=Undefined, annotation=None, name='', param_kind='POSITIONAL_OR_KEYWORD', label=None, gui_only=False, app=None, widget_type=None, options=None, is_result=False, raise_on_unknown=True)","text":"

Create and return appropriate widget subclass.

This factory function can be used to create a widget appropriate for the provided value and/or annotation provided. See Type Mapping Docs for details on how the widget type is determined from type annotations.

Parameters:

Returns:

Raises:

Examples:

from magicgui.widgets import create_widget\n\n# create a widget from a string value\nwdg = create_widget(value=\"hello world\")\nassert wdg.value == \"hello world\"\n\n# create a widget from a string annotation\nwdg = create_widget(annotation=str)\nassert wdg.value == \"\"\n
"},{"location":"generated_examples/","title":"Examples","text":""},{"location":"generated_examples/#getting-started","title":"Getting started","text":"

A gallery of examples for magicgui.

Basic example

Basic widgets demo

"},{"location":"generated_examples/#demo-applications","title":"Demo applications","text":"

Example applications built with magicgui.

Input values dialog

Quantities with pint

Callable functions demo

Snell's law demonstration using magicgui

Hotdog or not app

Chaining functions together

"},{"location":"generated_examples/#demo-widget-types","title":"Demo widget types","text":"

Example gallery demonstrating the available widget types in magicgui.

Image widget

Custom text labels for widgets

Range slider widget

Log slider widget

Optional user choice

Multiple selection widget

Password login

File dialog widget

Dropdown selection widget

Table widget

"},{"location":"generated_examples/#matplotlib-and-magicgui","title":"matplotlib and magicgui","text":"

Examples involving matplotlib graphs and magicgui.

matplotlib figure example

Waveforms example

"},{"location":"generated_examples/#napari-and-magicgui","title":"napari and magicgui","text":"

Examples integrating magicgui with napari.

napari forward reference demo

napari Qt demo

napari parameter sweeps

napari image arithmetic widget

"},{"location":"generated_examples/#jupyter-notebooks-and-magicgui","title":"Jupyter notebooks and magicgui","text":"

Examples using jupyter notebooks together with magicgui.

Jupyter notebooks and magicgui

"},{"location":"generated_examples/#progress-bar-examples","title":"Progress bar examples","text":"

Examples of progress bars in magicgui.

Manual progress bar

Simple progress bar

Indeterminate progress bar

Nested progress bars

"},{"location":"generated_examples/#under-the-hood","title":"Under the hood","text":"

Learn more advanced usage patterns for magicgui, including self referencing widgets and decorating class methods with magicgui.

Self reference magicgui widgets

Deocrate class methods with magicgui

Download all examples in Python source code: generated_examples_python.zip

Download all examples in Jupyter notebooks: generated_examples_jupyter.zip

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/basic_example/","title":"Basic example","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/basic_example/#basic-example","title":"Basic example","text":"

A basic example using magicgui.

Out:

<FunctionGui example(x: int = 0, y='hi')>\n

from magicgui import magicgui\n\n\n@magicgui\ndef example(x: int, y=\"hi\"):\n    \"\"\"Basic example function.\"\"\"\n    return x, y\n\n\nexample.changed.connect(print)\nexample.show(run=True)\n

Total running time of the script: ( 0 minutes 1.622 seconds)

Download Python source code: basic_example.py

Download Jupyter notebook: basic_example.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/basic_widgets_demo/","title":"Basic widgets demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/basic_widgets_demo/#basic-widgets-demo","title":"Basic widgets demo","text":"

Widget demonstration with magicgui.

This code demonstrates a few of the widget types that magicgui can create based on the parameter types in your function.

Out:

<MainFunctionGui widget_demo(boolean=True, integer=1, spin_float=3.14, slider_float=43.5, slider_int=550, string='Text goes here', dropdown=<Medium.Glass: 1.52>, radio_option=2, date=datetime.date(1999, 12, 31), time=datetime.time(1, 30, 20), datetime=datetime.datetime(2023, 10, 11, 20, 8, 39, 184000), filename=PosixPath('/Users/runner'))>\n

import datetime\nfrom enum import Enum\nfrom pathlib import Path\n\nfrom magicgui import magicgui\n\n\nclass Medium(Enum):\n    \"\"\"Enum for various media and their refractive indices.\"\"\"\n\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(\n    main_window=True,\n    call_button=\"Calculate\",\n    layout=\"vertical\",\n    result_widget=True,\n    slider_float={\"widget_type\": \"FloatSlider\", \"max\": 100},\n    slider_int={\"widget_type\": \"Slider\", \"readout\": False},\n    radio_option={\n        \"widget_type\": \"RadioButtons\",\n        \"orientation\": \"horizontal\",\n        \"choices\": [(\"first option\", 1), (\"second option\", 2)],\n    },\n    filename={\"label\": \"Pick a file:\"},\n)\ndef widget_demo(\n    boolean=True,\n    integer=1,\n    spin_float=3.14159,\n    slider_float=43.5,\n    slider_int=550,\n    string=\"Text goes here\",\n    dropdown=Medium.Glass,\n    radio_option=2,\n    date=datetime.date(1999, 12, 31),\n    time=datetime.time(1, 30, 20),\n    datetime=datetime.datetime.now(),\n    filename=Path.home(),\n):\n    \"\"\"We can use numpy docstrings to provide tooltips.\n\n    Parameters\n    ----------\n    boolean : bool, optional\n        A checkbox for booleans, by default True\n    integer : int, optional\n        Some integer, by default 1\n    spin_float : float, optional\n        This one is a float, by default \"pi\"\n    slider_float : float, optional\n        Hey look! I'm a slider, by default 43.5\n    slider_int : float, optional\n        I only take integers, and I've hidden my readout, by default 550\n    string : str, optional\n        We'll use this string carefully, by default \"Text goes here\"\n    dropdown : Enum, optional\n        Pick a medium, by default Medium.Glass\n    radio_option : int\n        A set of radio buttons.\n    date : datetime.date, optional\n        Your birthday, by default datetime.date(1999, 12, 31)\n    time : datetime.time, optional\n        Some time, by default datetime.time(1, 30, 20)\n    datetime : datetime.datetime, optional\n        A very specific time and date, by default ``datetime.datetime.now()``\n    filename : str, optional\n        Pick a path, by default Path.home()\n    \"\"\"\n    return locals().values()\n\n\nwidget_demo.changed.connect(print)\nwidget_demo.show(run=True)\n

Total running time of the script: ( 0 minutes 0.296 seconds)

Download Python source code: basic_widgets_demo.py

Download Jupyter notebook: basic_widgets_demo.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/mg_execution_times/","title":"Computation times","text":"

00:01.918 total execution time for generated_examples files:

+-------------------------------------------------------------------------------------+-----------+--------+ | basic_example (docs/examples/basic_example.py) | 00:01.622 | 0.0 MB | +-------------------------------------------------------------------------------------+-----------+--------+ | basic_widgets_demo (docs/examples/basic_widgets_demo.py) | 00:00.296 | 0.0 MB | +-------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/applications/callable/","title":"Callable functions demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/callable/#callable-functions-demo","title":"Callable functions demo","text":"

This example demonstrates handling callable functions with magicgui.

Out:

<FunctionGui example(func='f')>\n

from magicgui import magicgui\n\n\ndef f(x: int, y=\"a string\") -> str:\n    \"\"\"Example function F.\"\"\"\n    return f\"{y} {x}\"\n\n\ndef g(x: int = 6, y=\"another string\") -> str:\n    \"\"\"Example function G.\"\"\"\n    return f\"{y} asdfsdf {x}\"\n\n\n@magicgui(call_button=True, func={\"choices\": [\"f\", \"g\"]})\ndef example(func=\"f\"):\n    \"\"\"\u00cbxample function.\"\"\"\n    pass\n\n\ndef update(f: str):\n    \"\"\"Update function.\"\"\"\n    if len(example) > 2:\n        del example[1]\n    example.insert(1, magicgui(globals()[f]))\n\n\nexample.func.changed.connect(update)\nexample.show(run=True)\n

Total running time of the script: ( 0 minutes 0.077 seconds)

Download Python source code: callable.py

Download Jupyter notebook: callable.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/chaining/","title":"Chaining functions together","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/chaining/#chaining-functions-together","title":"Chaining functions together","text":"

This example demonstrates chaining multiple functions together.

Out:

calling func_a\ncalling func_b\ncalling func_c\n\n\n<Container (func_a: NoneType, func_b: NoneType, func_c: NoneType)>\n

from magicgui import magicgui, widgets\n\n\n@magicgui(auto_call=True)\ndef func_a(x: int = 64, y: int = 64):\n    \"\"\"Callable function A.\"\"\"\n    print(\"calling func_a\")\n    return x + y\n\n\n@magicgui(auto_call=True, input={\"visible\": False, \"label\": \" \", \"max\": 100000})\ndef func_b(input: int, mult=1.0):\n    \"\"\"Callable function B.\"\"\"\n    print(\"calling func_b\")\n    result = input * mult\n    # since these function defs live in globals(), you can update them directly\n    func_c.input.value = result\n    return result\n\n\n# alternatively, you can the `widget.called` signal to connect a callback function\n# where the result of the function being called is at `value`\n@func_a.called.connect\ndef _on_func_a(value: str):\n    func_b.input.value = value\n\n\n@magicgui(\n    auto_call=True,\n    input={\"visible\": False, \"max\": 100000},\n    result_widget=True,\n    labels=False,\n)\ndef func_c(input: int, format: str = \"({} + {}) * {} is {}\") -> str:\n    \"\"\"Callable function C.\"\"\"\n    print(\"calling func_c\\n\")\n    return format.format(func_a.x.value, func_a.y.value, func_b.mult.value, input)\n\n\ncontainer = widgets.Container(\n    widgets=[func_a, func_b, func_c], layout=\"vertical\", labels=False\n)\ncontainer.native.setMinimumWidth(500)\nfunc_a()\ncontainer.show(run=True)\n\n# notice which functions get called when you change each widget.\n

Total running time of the script: ( 0 minutes 0.111 seconds)

Download Python source code: chaining.py

Download Jupyter notebook: chaining.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/hotdog/","title":"Hotdog or not app","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/hotdog/#hotdog-or-not-app","title":"Hotdog or not app","text":"

Demo app to upload an image and classify if it's an hotdog or not.

import pathlib\nfrom enum import Enum\n\nfrom magicgui import magicgui\n\n\nclass HotdogOptions(Enum):\n    \"\"\"All hotdog possibilities.\"\"\"\n\n    Hotdog = 1\n    NotHotdog = 0\n\n\n@magicgui(main_window=True, layout=\"form\", call_button=\"Classify\", result_widget=True)\ndef is_hotdog(img: pathlib.Path) -> HotdogOptions:\n    \"\"\"Classify possible hotdog images.\n\n    Upload an image and check whether it's an hotdog. For example, this image\n    will be classified as one: <br><br>\n\n    <img src=\"resources/hotdog.jpg\">\n\n    Parameters\n    ----------\n    img : pathlib.Path\n        Path to a possible hotdog image\n\n    Returns\n    -------\n    HotdogOptions\n        True if image contains an hotdog in it\n    \"\"\"\n    if \"hotdog\" in img.stem:\n        return HotdogOptions.Hotdog\n    return HotdogOptions.NotHotdog\n\n\nif __name__ == \"__main__\":\n    is_hotdog.show(run=True)\n

Total running time of the script: ( 0 minutes 0.087 seconds)

Download Python source code: hotdog.py

Download Jupyter notebook: hotdog.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/mg_execution_times/","title":"Computation times","text":"

00:02.569 total execution time for generated_examples_applications files:

+-----------------------------------------------------------------------------------+-----------+--------+ | pint_quantity (docs/examples/applications/pint_quantity.py) | 00:02.190 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | chaining (docs/examples/applications/chaining.py) | 00:00.111 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | snells_law (docs/examples/applications/snells_law.py) | 00:00.104 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | hotdog (docs/examples/applications/hotdog.py) | 00:00.087 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | callable (docs/examples/applications/callable.py) | 00:00.077 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+ | values_dialog (docs/examples/applications/values_dialog.py) | 00:00.000 | 0.0 MB | +-----------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/applications/pint_quantity/","title":"Quantities with pint","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/pint_quantity/#quantities-with-pint","title":"Quantities with pint","text":"

Pint is a Python package to define, operate and manipulate physical quantities: the product of a numerical value and a unit of measurement. It allows arithmetic operations between them and conversions from and to different units. https://pint.readthedocs.io/en/stable/

Out:

<FunctionGui widget(q=<Quantity(1, 'millisecond')>)>\n

from pint import Quantity\n\nfrom magicgui import magicgui\n\n\n@magicgui\ndef widget(q=Quantity(\"1 ms\")):\n    \"\"\"Widget allowing users to input quantity measurements.\"\"\"\n    print(q)\n\n\nwidget.show(run=True)\n

Total running time of the script: ( 0 minutes 2.190 seconds)

Download Python source code: pint_quantity.py

Download Jupyter notebook: pint_quantity.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/snells_law/","title":"Snell's law demonstration using magicgui","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/snells_law/#snells-law-demonstration-using-magicgui","title":"Snell's law demonstration using magicgui","text":"

Demo app for calculating angles of refraction according to Snell's law.

Out:

<FunctionGui snells_law(aoi=1.0, n1=<Medium.Glass: 1.52>, n2=<Medium.Water: 1.333>, degrees=True)>\n

import math\nfrom enum import Enum\n\nfrom magicgui import magicgui\n\n\nclass Medium(Enum):\n    \"\"\"Enum for various media and their refractive indices.\"\"\"\n\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(call_button=\"calculate\", result_widget=True)\ndef snells_law(aoi=1.0, n1=Medium.Glass, n2=Medium.Water, degrees=True):\n    \"\"\"Calculate the angle of refraction given two media and an AOI.\"\"\"\n    if degrees:\n        aoi = math.radians(aoi)\n    try:\n        n1 = n1.value\n        n2 = n2.value\n        result = math.asin(n1 * math.sin(aoi) / n2)\n        return round(math.degrees(result) if degrees else result, 2)\n    except ValueError:  # math domain error\n        return \"TIR!\"\n\n\nsnells_law.show(run=True)\n

Total running time of the script: ( 0 minutes 0.104 seconds)

Download Python source code: snells_law.py

Download Jupyter notebook: snells_law.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/applications/values_dialog/","title":"Input values dialog","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/applications/values_dialog/#input-values-dialog","title":"Input values dialog","text":"

A basic example of a user input dialog.

This will pause code execution until the user responds.

"},{"location":"generated_examples/applications/values_dialog/#_1","title":"Input values dialog","text":"
from magicgui.widgets import request_values\n\nvals = request_values(\n    age=int,\n    name={\"annotation\": str, \"label\": \"Enter your name:\"},\n    title=\"Hi, who are you?\",\n)\nprint(repr(vals))\n

Total running time of the script: ( 0 minutes 0.000 seconds)

Download Python source code: values_dialog.py

Download Jupyter notebook: values_dialog.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/change_label/","title":"Custom text labels for widgets","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/change_label/#custom-text-labels-for-widgets","title":"Custom text labels for widgets","text":"

An example showing how to create custom text labels for your widgets.

Out:

<FunctionGui example(x=1, y='hi')>\n

from magicgui import magicgui\n\n\n# use a different label than the default (the parameter name) in the UI\n@magicgui(x={\"label\": \"widget to set x\"})\ndef example(x=1, y=\"hi\"):\n    \"\"\"Example function.\"\"\"\n    return x, y\n\n\nexample.changed.connect(print)\nexample.show(run=True)\n

Total running time of the script: ( 0 minutes 0.082 seconds)

Download Python source code: change_label.py

Download Jupyter notebook: change_label.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/choices/","title":"Dropdown selection widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/choices/#dropdown-selection-widget","title":"Dropdown selection widget","text":"

Choices for dropdowns can be provided in a few different ways.

Out:

<Container (as_list: NoneType, as_enum: NoneType, as_2tuple: NoneType, as_function: NoneType)>\n

from enum import Enum\n\nfrom magicgui import magicgui, widgets\n\n\nclass Medium(Enum):\n    \"\"\"Enum for various media and their refractive indices.\"\"\"\n\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(ri={\"choices\": [\"Oil\", \"Water\", \"Air\"]}, auto_call=True)\ndef as_list(ri=\"Water\"):\n    \"\"\"Function decorated with magicgui list of choices.\"\"\"\n    print(\"refractive index is\", Medium[ri].value)\n\n\n@magicgui(auto_call=True)\ndef as_enum(ri: Medium = Medium.Water):\n    \"\"\"Function decorated with magicgui and enumeration.\"\"\"\n    print(\"refractive index is\", ri.value)\n\n\n@magicgui(\n    ri={\"choices\": [(\"Oil\", 1.515), (\"Water\", 1.33), (\"Air\", 1.0)]}, auto_call=True\n)\ndef as_2tuple(ri=1.33):\n    \"\"\"Function decorated with magicgui tuple of choices.\"\"\"\n    print(\"refractive index is\", ri)\n\n\ndef get_choices(gui):\n    \"\"\"Function returning tuple of material and refractive index value.\"\"\"\n    return [(\"Oil\", 1.515), (\"Water\", 1.33), (\"Air\", 1.0)]\n\n\n@magicgui(ri={\"choices\": get_choices}, auto_call=True)\ndef as_function(ri: float):\n    \"\"\"Function to calculate refractive index.\"\"\"\n    print(\"refractive index is\", ri)\n\n\ncontainer = widgets.Container(\n    widgets=[as_list, as_enum, as_2tuple, as_function], layout=\"vertical\"\n)\ncontainer.show(run=True)\n

Total running time of the script: ( 0 minutes 0.113 seconds)

Download Python source code: choices.py

Download Jupyter notebook: choices.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/file_dialog/","title":"File dialog widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/file_dialog/#file-dialog-widget","title":"File dialog widget","text":"

A file dialog widget example.

* ![file dialog](../images/mkd_glr_file_dialog_001.png){: .mkd-glr-multi-img srcset=\"../images/mkd_glr_file_dialog_001.png\"}\n\n* ![file dialog](../images/mkd_glr_file_dialog_002.png){: .mkd-glr-multi-img srcset=\"../images/mkd_glr_file_dialog_002.png\"}\n\n* ![file dialog](../images/mkd_glr_file_dialog_003.png){: .mkd-glr-multi-img srcset=\"../images/mkd_glr_file_dialog_003.png\"}\n
from pathlib import Path\nfrom typing import Sequence\n\nfrom magicgui import magicgui, use_app\n\n\n@magicgui(filename={\"mode\": \"r\"})\ndef filepicker(filename=Path(\"~\")):\n    \"\"\"Take a filename and do something with it.\"\"\"\n    print(\"The filename is:\", filename)\n    return filename\n\n\n# Sequence of paths\n# We change the label using \"label\" for added clarity\n# the filter argument restricts file types\n@magicgui(filenames={\"label\": \"Choose Tiff files:\", \"filter\": \"*.tif\"})\ndef filespicker(filenames: Sequence[Path]):\n    \"\"\"Take a filename and do something with it.\"\"\"\n    print(\"The filenames are:\", filenames)\n    return filenames\n\n\n# Select a directory, instead of file(s)\n@magicgui(directory={\"mode\": \"d\", \"label\": \"Choose a directory\"})\ndef directorypicker(directory=Path(\"~\")):\n    \"\"\"Take a directory name and do something with it.\"\"\"\n    print(\"The directory name is:\", directory)\n    return directory\n\n\nfilepicker.show()\nfilespicker.show()\ndirectorypicker.show()\nfilepicker.filename.changed.connect(print)\nfilespicker.filenames.changed.connect(print)\ndirectorypicker.directory.changed.connect(print)\n\nuse_app().run()\n

Total running time of the script: ( 0 minutes 0.169 seconds)

Download Python source code: file_dialog.py

Download Jupyter notebook: file_dialog.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/image/","title":"Image widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/image/#image-widget","title":"Image widget","text":"

Example of creating an Image Widget from a file.

(This requires pillow, or that magicgui was installed as magicgui[image])

Out:

Image(200x232x3, name='')\n

from magicgui.widgets import Image\n\nimage = Image(value=\"../../images/_test.jpg\")\nimage.scale_widget_to_image_size()\nimage.show(run=True)\n

Total running time of the script: ( 0 minutes 0.062 seconds)

Download Python source code: image.py

Download Jupyter notebook: image.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/log_slider/","title":"Log slider widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/log_slider/#log-slider-widget","title":"Log slider widget","text":"

A logarithmic scale range slider widget.

Out:

<FunctionGui slider(input=1.0)>\n

from magicgui import magicgui\n\n\n@magicgui(\n    auto_call=True,\n    result_widget=True,\n    input={\"widget_type\": \"LogSlider\", \"max\": 10000, \"min\": 1, \"tracking\": False},\n)\ndef slider(input=1):\n    \"\"\"Logarithmic scale slider.\"\"\"\n    return round(input, 4)\n\n\nslider.show(run=True)\n

Total running time of the script: ( 0 minutes 0.090 seconds)

Download Python source code: log_slider.py

Download Jupyter notebook: log_slider.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/login/","title":"Password login","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/login/#password-login","title":"Password login","text":"

A password login field widget.

Out:

<FunctionGui login(username: str = '', password: str = '', password2: str = '')>\n

from magicgui import magicgui\n\n\n# note that \"password\" is a special keyword argument\n# it will create a password field in the gui by default\n# (unless you override \"widget_type\")\n# whereas \"password2\" will be a normal text field\n# (unless you override \"widget_type\")\n@magicgui(password2={\"widget_type\": \"Password\"})\ndef login(username: str, password: str, password2: str):\n    \"\"\"User login credentials.\"\"\"\n    ...\n\n\nlogin.show(run=True)\n

Total running time of the script: ( 0 minutes 0.086 seconds)

Download Python source code: login.py

Download Jupyter notebook: login.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/mg_execution_times/","title":"Computation times","text":"

00:01.021 total execution time for generated_examples_demo_widgets files:

+--------------------------------------------------------------------------------+-----------+--------+ | file_dialog (docs/examples/demo_widgets/file_dialog.py) | 00:00.169 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | range_slider (docs/examples/demo_widgets/range_slider.py) | 00:00.155 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | choices (docs/examples/demo_widgets/choices.py) | 00:00.113 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | table (docs/examples/demo_widgets/table.py) | 00:00.098 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | selection (docs/examples/demo_widgets/selection.py) | 00:00.090 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | log_slider (docs/examples/demo_widgets/log_slider.py) | 00:00.090 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | login (docs/examples/demo_widgets/login.py) | 00:00.086 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | change_label (docs/examples/demo_widgets/change_label.py) | 00:00.082 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | optional (docs/examples/demo_widgets/optional.py) | 00:00.077 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+ | image (docs/examples/demo_widgets/image.py) | 00:00.062 | 0.0 MB | +--------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/demo_widgets/optional/","title":"Optional user choice","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/optional/#optional-user-choice","title":"Optional user choice","text":"

Optional user input using a dropdown selection widget.

Out:

<FunctionGui f(path: str = None)>\n

from typing import Optional\n\nfrom magicgui import magicgui\n\n\n# Using optional will add a '----' to the combobox, which returns \"None\"\n@magicgui(path={\"choices\": [\"a\", \"b\"]})\ndef f(path: Optional[str] = None):\n    \"\"\"\u00d6ptional user input function.\"\"\"\n    print(path, type(path))\n\n\nf.show(run=True)\n

Total running time of the script: ( 0 minutes 0.077 seconds)

Download Python source code: optional.py

Download Jupyter notebook: optional.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/range_slider/","title":"Range slider widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/range_slider/#range-slider-widget","title":"Range slider widget","text":"

A double ended range slider widget.

Out:

<FunctionGui func(range_value: Tuple[int, int] = (20, 380))>\n

from typing import Tuple\n\nfrom magicgui import magicgui\n\n\n@magicgui(auto_call=True, range_value={\"widget_type\": \"RangeSlider\", \"max\": 500})\ndef func(range_value: Tuple[int, int] = (20, 380)):\n    \"\"\"Double ended range slider.\"\"\"\n    print(range_value)\n\n\nfunc.show(run=True)\n

Total running time of the script: ( 0 minutes 0.155 seconds)

Download Python source code: range_slider.py

Download Jupyter notebook: range_slider.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/selection/","title":"Multiple selection widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/selection/#multiple-selection-widget","title":"Multiple selection widget","text":"

A selection widget allowing multiple selections by the user.

Out:

<FunctionGui my_widget(pick_some=['first'])>\n

from magicgui import magicgui\n\n\n@magicgui(\n    pick_some={\n        \"choices\": (\"first\", \"second\", \"third\", \"fourth\"),\n        \"allow_multiple\": True,\n    }\n)\ndef my_widget(pick_some=(\"first\")):\n    \"\"\"Dropdown selection function.\"\"\"\n    print(\"you selected\", pick_some)\n\n\nmy_widget.show(run=True)\n

Total running time of the script: ( 0 minutes 0.090 seconds)

Download Python source code: selection.py

Download Jupyter notebook: selection.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/demo_widgets/table/","title":"Table widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/demo_widgets/table/#table-widget","title":"Table widget","text":"

Demonstrating a few ways to input tables.

Out:

Table(shape=(6, 3) at 0x13a1b9b50)\n

import numpy as np\n\nfrom magicgui.widgets import Table\n\n# all of these are valid data types\ndict_of_lists = {\"col_1\": [1, 4], \"col_2\": [2, 5], \"col_3\": [3, 6]}\n# column-dict-of-row-dicts\ndict_of_dict = {\n    \"col_1\": {\"r1\": 1, \"r2\": 4},\n    \"col_2\": {\"r1\": 2, \"r2\": 5},\n    \"col_3\": {\"r1\": 3, \"r2\": 6},\n}\n# list-of-lists\nlist_of_list = [[1, 2, 3], [4, 5, 6]]\n# Records: List-of-column-dict\nlist_of_records = [\n    {\"col_1\": 1, \"col_2\": 2, \"col_3\": 3},\n    {\"col_1\": 4, \"col_2\": 5, \"col_3\": 6},\n]\n\n# 3-tuple of data, index, column\ndata_index_column_tuple = (([[1, 2, 3], [4, 5, 6]], (\"r1\", \"r2\"), (\"c1\", \"c2\", \"c3\")),)\n# split-dict\nsplit_dict = {\n    \"data\": [[1, 2, 3], [4, 5, 6]],\n    \"index\": (\"r1\", \"r2\"),\n    \"columns\": (\"c1\", \"c2\", \"c3\"),\n}\n\ntable = Table(value=dict_of_lists)\n\n# it behaves like a dict:\ntable[\"new_col\"] = [5, 5]\nassert table.pop(\"new_col\") == [5, 5]\n# keys and items have both regular (column) and \"row\" modes\ncol_item_view = table.items()  # iterate col_header/column\nrow_item_view = table.items(\"row\")  # iterate row_header/row\n\n# we can just call dict() to get back our dict of lists\nassert dict(table) == dict_of_lists\n# or use one of many other exports in `to_dict`\nassert table.to_dict(\"records\") == list_of_records\n\n# change headers\ntable.row_headers = (\"row1\", \"row2\")\ntable.column_headers = (\"a\", \"b\", \"c\")\n\n# setting value clears and resets the table:\ntable.value = np.arange(18).reshape(6, 3)\n# we can get/set/delete the 2D data table using numpy-style indexing:\n# get every other row\nassert table.data[::2] == [[0, 1, 2], [6, 7, 8], [12, 13, 14]]\n# set every other column in the 3rd row\ntable.data[2, ::2] = [99, 99]\n\n# export to numpy or pandas\n# table.data.to_numpy()\n# table.to_dataframe()\n\n# the table.changed event emits a dict of information on any cell change\n# e.g. {'data': 'sdfg', 'row': 1, 'column': 0, 'column_header': '1', 'row_header': '1'}\ntable.changed.connect(print)\ntable.show(run=True)\n

Total running time of the script: ( 0 minutes 0.098 seconds)

Download Python source code: table.py

Download Jupyter notebook: table.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/matplotlib/mg_execution_times/","title":"Computation times","text":"

00:00.920 total execution time for generated_examples_matplotlib files:

+------------------------------------------------------------------------+-----------+--------+ | waveform (docs/examples/matplotlib/waveform.py) | 00:00.562 | 0.0 MB | +------------------------------------------------------------------------+-----------+--------+ | mpl_figure (docs/examples/matplotlib/mpl_figure.py) | 00:00.359 | 0.0 MB | +------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/matplotlib/mpl_figure/","title":"matplotlib figure example","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/matplotlib/mpl_figure/#matplotlib-figure-example","title":"matplotlib figure example","text":"

Basic example of adding a generic QWidget to a container.

Main lesson: add your QWidget to container.native.layout() as shown on line 30

Out:

<FunctionGui f(position: int = 0)>\n

import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\n\nfrom magicgui import magicgui\n\nx = np.linspace(0, 5, 256)\ny = np.linspace(0, 5, 256)[:, np.newaxis]\ndata = np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)\n\nmpl_fig = plt.figure()\nax = mpl_fig.add_subplot(111)\n(line,) = ax.plot(data[123])  # linescan through the middle of the image\n\n\n@magicgui(position={\"widget_type\": \"Slider\", \"max\": 255}, auto_call=True)\ndef f(position: int):\n    \"\"\"Function demonstrating magicgui combined with matplotlib.\"\"\"\n    line.set_ydata(data[position])\n    line.figure.canvas.draw()\n\n\n# rather than using the Container.append (`f.append`) ...\n# grab the native layout and add the QWidget to it\nf.native.layout().addWidget(FigureCanvas(mpl_fig))\n\nf.show(run=True)\n

Total running time of the script: ( 0 minutes 0.359 seconds)

Download Python source code: mpl_figure.py

Download Jupyter notebook: mpl_figure.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/matplotlib/waveform/","title":"Waveforms example","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/matplotlib/waveform/#waveforms-example","title":"Waveforms example","text":"

Simple waveform generator widget, with plotting.

Out:

<Container (signal_widget: NoneType, sine: NoneType)>\n

from dataclasses import dataclass, field\nfrom enum import Enum\nfrom functools import partial\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_qt5agg import FigureCanvas\nfrom scipy import signal\nfrom typing_extensions import Annotated\n\nfrom magicgui import magicgui, register_type, widgets\n\nregister_type(float, widget_type=\"FloatSlider\")\nregister_type(int, widget_type=\"Slider\")\n\nFreq = Annotated[float, {\"min\": 0.001, \"max\": 30.0}]\nPhase = Annotated[float, {\"min\": 0.0, \"max\": 360.0}]\nDuty = Annotated[float, {\"min\": 0.0, \"max\": 1.0}]\nTime = Annotated[float, {\"min\": 0.01, \"max\": 100.0}]\n\n\n@dataclass\nclass Signal:\n    \"\"\"Constructs a 1D signal.\n\n    As is, this class is not very useful, but one could add callbacks\n    or more functionality here\n\n    Parameters\n    ----------\n    func : callable\n        func must take a 'time' array as sole argument and return a 1D array with the\n        same size as the input\n    duration : float\n        the maximum of the input time array\n    size : int\n        the number of samples in the time array\n\n    \"\"\"\n\n    func: callable\n    duration: Time = 1.0\n    size: int = 500\n    time: np.ndarray = field(init=False)\n    data: np.ndarray = field(init=False)\n\n    def __post_init__(self):\n        \"\"\"Evaluate the function at instantiation time.\"\"\"\n        self.time = np.linspace(0, self.duration, self.size)\n        self.data = self.func(self.time)\n\n    def plot(self, ax=None, **kwargs):\n        \"\"\"Plots the data.\n\n        Parameters\n        ----------\n        ax: matplotlib.axes.Axes instance, default None\n           if provided the plot is done on this axes instance.\n           If None a new ax is created\n        **kwargs: Keyword arguments that are passed on to\n            the matplotib ax.plot method\n\n        Returns\n        -------\n        fig: a matplotlib.figure.Figure instance\n        ax: matplotlib.axes.Axes instance\n        \"\"\"\n        if ax is None:\n            fig, ax = plt.subplots()\n        else:\n            fig = ax.get_figure()\n        ax.plot(self.time, self.data, **kwargs)\n        return fig, ax\n\n\ndef sine(\n    duration: Time = 10.0, size: int = 500, freq: Freq = 0.5, phase: Phase = 0.0\n) -> Signal:\n    \"\"\"Returns a 1D sine wave.\n\n    Parameters\n    ----------\n    duration: float\n       the duration of the signal in seconds\n    size: int\n        the number of samples in the signal time array\n    freq: float\n       the frequency of the signal in Hz\n    phase: Phase\n       the phase of the signal (in degrees)\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=lambda t: np.sin(t * (2 * np.pi * freq) + phase * np.pi / 180),\n    )\n    return sig\n\n\ndef chirp(\n    duration: Time = 10.0,\n    size: int = 500,\n    f0: float = 1.0,\n    t1: Time = 5.0,\n    f1: float = 2.0,\n    phase: Phase = 0.0,\n) -> Signal:\n    \"\"\"Frequency-swept cosine generator.\n\n    See scipy.signal.chirp\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=partial(signal.chirp, f0=f0, t1=t1, f1=f1, phi=phase),\n    )\n    return sig\n\n\ndef sawtooth(\n    duration: Time = 10.0,\n    size: int = 500,\n    freq: Freq = 1.0,\n    width: Duty = 1.0,\n    phase: Phase = 0.0,\n) -> Signal:\n    \"\"\"Return a periodic sawtooth or triangle waveform.\n\n    See scipy.signal.sawtooth\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=lambda t: signal.sawtooth(\n            2 * np.pi * freq * t + phase * np.pi / 180, width=width\n        ),\n    )\n    return sig\n\n\ndef square(\n    duration: Time = 10.0, size: int = 500, freq: Freq = 1.0, duty: Duty = 0.5\n) -> Signal:\n    \"\"\"Return a periodic sawtooth or triangle waveform.\n\n    See scipy.signal.square\n    \"\"\"\n    sig = Signal(\n        duration=duration,\n        size=size,\n        func=lambda t: signal.square(2 * np.pi * freq * t, duty=duty),\n    )\n    return sig\n\n\ndef on_off(\n    duration: Time = 10.0, size: int = 500, t_on: Time = 0.01, t_off: Time = 0.01\n) -> Signal:\n    \"\"\"On/Off signal function.\"\"\"\n    data = np.ones(size)\n    data[: int(size * t_on / duration)] = -1\n    if t_off > 0:\n        data[int(size * t_off / duration) :] = -1\n    sig = Signal(duration=duration, size=size, func=lambda t: data)\n    return sig\n\n\nWAVEFORMS = {\n    \"sine\": sine,\n    \"chirp\": chirp,\n    \"sawtooth\": sawtooth,\n    \"square\": square,\n    \"on_off\": on_off,\n}\n\n\nclass Select(Enum):\n    \"\"\"Enumeration to select signal type.\"\"\"\n\n    OnOff = \"on_off\"\n    Sine = \"sine\"\n    Chirp = \"chirp\"\n    Sawtooth = \"sawtooth\"\n    Square = \"square\"\n\n\nclass WaveForm(widgets.Container):\n    \"\"\"Simple waveform generator widget, with plotting.\"\"\"\n\n    def __init__(self):\n        \"\"\"Creates the widget.\"\"\"\n        super().__init__()\n        self.fig, self.ax = plt.subplots()\n        self.native.layout().addWidget(FigureCanvas(self.fig))\n        self.waveform = sine\n        self.controls = None\n        self.append(self.signal_widget)\n        self.update_controls()\n        self.update_graph(sine())\n\n    @magicgui(auto_call=True)\n    def signal_widget(self, select: Select = Select.Sine) -> widgets.Container:\n        \"\"\"Waveform selection, from the WAVEFORMS dict.\"\"\"\n        self.waveform = WAVEFORMS[select.value]\n        self.update_controls()\n        self.update_graph(self.waveform())\n\n    def update_controls(self):\n        \"\"\"Reset controls according to the new function.\"\"\"\n        if self.controls is not None:\n            self.remove(self.controls)\n        self.controls = magicgui(auto_call=True)(self.waveform)\n        self.append(self.controls)\n        self.controls.called.connect(self.update_graph)\n\n    def update_graph(self, sig: Signal):\n        \"\"\"Re-plot when a parameter changes.\n\n        Note\n        ----\n        For big data, this could be slow, maybe `auto_call` should\n        not be true in the method above...\n        \"\"\"\n        self.ax.cla()\n        sig.plot(ax=self.ax)\n        self.fig.canvas.draw()\n\n\nwaveform = WaveForm()\nwaveform.show(run=True)\n

Total running time of the script: ( 0 minutes 0.562 seconds)

Download Python source code: waveform.py

Download Jupyter notebook: waveform.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/mg_execution_times/","title":"Computation times","text":"

00:25.609 total execution time for generated_examples_napari files:

+--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_combine_qt (docs/examples/napari/napari_combine_qt.py) | 00:17.132 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_parameter_sweep (docs/examples/napari/napari_parameter_sweep.py) | 00:04.880 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_img_math (docs/examples/napari/napari_img_math.py) | 00:03.485 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+ | napari_forward_refs (docs/examples/napari/napari_forward_refs.py) | 00:00.112 | 0.0 MB | +--------------------------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/napari/napari_combine_qt/","title":"napari Qt demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_combine_qt/#napari-qt-demo","title":"napari Qt demo","text":"

Napari provides a few conveniences with magicgui, and one of the most commonly used is the layer combo box that gets created when a parameter is annotated as napari.layers.Layer.

The layer box will stay in sync with the viewer model, adding and removing layers as needed.

This example shows how to use just that widget in the context of a larger custom QWidget.

Out:

0.00s - Debugger warning: It seems that frozen modules are being used, which may\n0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off\n0.00s - to python to disable frozen modules.\n0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.\n

import napari\nfrom qtpy.QtWidgets import QVBoxLayout, QWidget\n\nfrom magicgui.widgets import create_widget\n\n\nclass CustomWidget(QWidget):\n    \"\"\"A custom widget class.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n        self.setLayout(QVBoxLayout())\n        # change annotation to napari.layers.Image (e.g) to restrict to just Images\n        self._layer_combo = create_widget(annotation=napari.layers.Layer)\n        # magicgui widgets hold the Qt widget at `widget.native`\n        self.layout().addWidget(self._layer_combo.native)\n\n\nviewer = napari.Viewer()\nviewer.add_points()\nviewer.add_points()\n\nmy_widget = CustomWidget()\nviewer.window.add_dock_widget(my_widget)\n\n# when my_widget is a magicgui.Widget, it will detect that it has been added\n# to a viewer, and automatically update the choices.  Otherwise, you need to\n# trigger this yourself:\nmy_widget._layer_combo.reset_choices()\nviewer.layers.events.inserted.connect(my_widget._layer_combo.reset_choices)\nviewer.layers.events.removed.connect(my_widget._layer_combo.reset_choices)\n\nnapari.run()\n

Total running time of the script: ( 0 minutes 17.132 seconds)

Download Python source code: napari_combine_qt.py

Download Jupyter notebook: napari_combine_qt.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/napari_forward_refs/","title":"napari forward reference demo","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_forward_refs/#napari-forward-reference-demo","title":"napari forward reference demo","text":"

Example of using a ForwardRef to avoid importing a module that provides a widget.

In this example, one might want to create a widget that takes as an argument a napari Image layer, and returns an Image. In order to avoid needing to import napari (and therefore depending directly on napari), it's possible to annotate those parameters with a string representation of the type (rather than the type itself). This is called a \"forward reference\": https://www.python.org/dev/peps/pep-0484/#forward-references

Out:

<FunctionGui subtract_background(data: napari.types.ImageData = None, background: int = 50) -> napari.types.ImageData>\n

# Note: if you'd like to avoid circular imports, or just want to avoid having your\n# linter yell at you for an undefined type annotation, you can place the import\n# inside of an `if typing.TYPE_CHECKING` conditional.  This is not evaluated at runtime,\n# only when something like mypy is doing type checking.\nfrom typing import TYPE_CHECKING\n\nfrom magicgui import magicgui\n\nif TYPE_CHECKING:\n    import napari\n\n\n@magicgui(call_button=\"execute\", background={\"max\": 200})\ndef subtract_background(\n    data: \"napari.types.ImageData\", background: int = 50\n) -> \"napari.types.ImageData\":\n    \"\"\"Subtract a constant from the data.\"\"\"\n    if data:\n        return data - background\n\n\nsubtract_background.show(run=True)\n# now, this example isn't all that interesting on its own (since there will be no Image\n# layer in the dropdown) ... but in another package, where you DO import napari,\n# you could add this widget to a napari viewer with\n# viewer.window.add_dock_widget(subtract_background)\n

Total running time of the script: ( 0 minutes 0.112 seconds)

Download Python source code: napari_forward_refs.py

Download Jupyter notebook: napari_forward_refs.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/napari_img_math/","title":"napari image arithmetic widget","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_img_math/#napari-image-arithmetic-widget","title":"napari image arithmetic widget","text":"

napari is a fast, interactive, multi-dimensional image viewer for python. It uses Qt for the GUI, so it's easy to extend napari with small, composable widgets created with magicgui. Here we're going to build this simple image arithmetic widget with a few additional lines of code.

For napari-specific magicgui documentation, see the napari docs

"},{"location":"generated_examples/napari/napari_img_math/#outline","title":"outline","text":"

This example demonstrates how to:

  1. Create a magicgui widget that can be used in another program (napari)

  2. Use an Enum to create a dropdown menu

  3. Connect some event listeners to create interactivity.

"},{"location":"generated_examples/napari/napari_img_math/#code","title":"code","text":"

Code follows, with explanation below... You can also get this example at github.

from enum import Enum\n\nimport napari\nimport numpy\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\nclass Operation(Enum):\n    # A set of valid arithmetic operations for image_arithmetic.\n    #\n    # To create nice dropdown menus with magicgui, it's best\n    # (but not required) to use Enums.  Here we make an Enum\n    # class for all of the image math operations we want to\n    # allow.\n    add = numpy.add\n    subtract = numpy.subtract\n    multiply = numpy.multiply\n    divide = numpy.divide\n\n\n# here's the magicgui!  We also use the additional\n# `call_button` option\n@magicgui(call_button=\"execute\")\ndef image_arithmetic(\n    layerA: ImageData, operation: Operation, layerB: ImageData\n) -> ImageData:\n    # Add, subtracts, multiplies, or divides to image layers.\n    return operation.value(layerA, layerB)\n\n# create a viewer and add a couple image layers\nviewer = napari.Viewer()\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 1\")\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 2\")\n\n# add our new magicgui widget to the viewer\nviewer.window.add_dock_widget(image_arithmetic)\n\n# keep the dropdown menus in the gui in sync with the layer model\nviewer.layers.events.inserted.connect(image_arithmetic.reset_choices)\nviewer.layers.events.removed.connect(image_arithmetic.reset_choices)\n\nnapari.run()\n
"},{"location":"generated_examples/napari/napari_img_math/#walkthrough","title":"walkthrough","text":"

We're going to go a little out of order so that the other code makes more sense. Let's start with the actual function we'd like to write to do some image arithmetic.

"},{"location":"generated_examples/napari/napari_img_math/#the-function","title":"the function","text":"

Our function takes two numpy arrays (in this case, from Image layers), and some mathematical operation (we'll restrict the options using an enum.Enum). When called, ourfunction calls the selected operation on the data.

def image_arithmetic(array1, operation, array2):\n    return operation.value(array1, array2)\n
"},{"location":"generated_examples/napari/napari_img_math/#type-annotations","title":"type annotations","text":"

magicgui works particularly well with type annotations, and allows third-party libraries to register widgets and behavior for handling their custom types (using magicgui.type_map.register_type). napari provides support for magicgui by registering a dropdown menu whenever a function parameter is annotated as one of the basic napari Layer types, or, in this case, ImageData indicates we just the data attribute of the layer. Furthermore, it recognizes when a function has a napari.layers.Layer or LayerData return type annotation, and will add the result to the viewer. So we gain a lot by annotating the above function with the appropriate napari types.

from napari.types import ImageData\n\ndef image_arithmetic(\n    layerA: ImageData, operation: Operation, layerB: ImageData\n) -> ImageData:\n    return operation.value(layerA, layerB)\n
"},{"location":"generated_examples/napari/napari_img_math/#the-magic-part","title":"the magic part","text":"

Finally, we decorate the function with @magicgui and tell it we'd like to have a call_button that we can click to execute the function.

@magicgui(call_button=\"execute\")\ndef image_arithmetic(layerA: ImageData, operation: Operation, layerB: ImageData):\n    return operation.value(layerA, layerB)\n

That's it! The image_arithmetic function is now a FunctionGui that can be shown, or incorporated into other GUIs (such as the napari GUI shown in this example)

!!! note While type hints aren't always required in magicgui, they are recommended ... and they are required for certain things, like the Operation(Enum) used here for the dropdown and the napari.types.ImageData annotations that napari has registered with magicgui.

"},{"location":"generated_examples/napari/napari_img_math/#create-dropdowns-with-enums","title":"create dropdowns with Enums","text":"

We'd like the user to be able to select the operation (add, subtract, multiply, divide) using a dropdown menu. enum.Enum offers a convenient way to restrict values to a strict set of options, while providing name: value pairs for each of the options. Here, the value for each choice is the actual function we would like to have called when that option is selected.

class Operation(enum.Enum):\n    add = numpy.add\n    subtract = numpy.subtract\n    multiply = numpy.multiply\n    divide = numpy.divide\n
"},{"location":"generated_examples/napari/napari_img_math/#add-it-to-napari","title":"add it to napari","text":"

When we decorated the image_arithmetic function above, it became a FunctionGui. Napari recognizes this type, so we can simply add it to the napari viewer as follows:

viewer.window.add_dock_widget(image_arithmetic)\n
"},{"location":"generated_examples/napari/napari_img_math/#connect-event-listeners-for-interactivity","title":"connect event listeners for interactivity","text":"

What fun is a GUI without some interactivity? Let's make stuff happen.

We connect the image_arithmetic.reset_choices function to the viewer.layers.events.inserted/removed event from napari, to make sure that the dropdown menus stay in sync if a layer gets added or removed from the napari window:

viewer.layers.events.inserted.connect(image_arithmetic.reset_choices)\nviewer.layers.events.removed.connect(image_arithmetic.reset_choices)\n

Tip

An additional offering from magicgui here is that the decorated function also acquires a new attribute \"called\" that can be connected to callback functions of your choice. Then, whenever the gui widget or the original function are called, the result will be passed to your callback function:

@image_arithmetic.called.connect\ndef print_mean(value):\n    # Callback function that accepts an event\n    # the value attribute has the result of calling the function\n    print(np.mean(value))\n
>>> image_arithmetic()\n1.0060037881040373\n
"},{"location":"generated_examples/napari/napari_img_math/#code_1","title":"Code","text":"

Here's the full code example again.

from enum import Enum\n\nimport napari\nimport numpy\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\nclass Operation(Enum):\n    # A set of valid arithmetic operations for image_arithmetic.\n    #\n    # To create nice dropdown menus with magicgui, it's best\n    # (but not required) to use Enums.  Here we make an Enum\n    # class for all of the image math operations we want to\n    # allow.\n    add = numpy.add\n    subtract = numpy.subtract\n    multiply = numpy.multiply\n    divide = numpy.divide\n\n\n# here's the magicgui!  We also use the additional\n# `call_button` option\n@magicgui(call_button=\"execute\")\ndef image_arithmetic(\n    layerA: ImageData, operation: Operation, layerB: ImageData\n) -> ImageData:\n    # Add, subtracts, multiplies, or divides to image layers.\n    return operation.value(layerA, layerB)\n\n\n# create a viewer and add a couple image layers\nviewer = napari.Viewer()\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 1\")\nviewer.add_image(numpy.random.rand(20, 20), name=\"Layer 2\")\n\n# add our new magicgui widget to the viewer\nviewer.window.add_dock_widget(image_arithmetic)\n\n# keep the dropdown menus in the gui in sync with the layer model\nviewer.layers.events.inserted.connect(image_arithmetic.reset_choices)\nviewer.layers.events.removed.connect(image_arithmetic.reset_choices)\n\nnapari.run()\n

Total running time of the script: ( 0 minutes 3.485 seconds)

Download Python source code: napari_img_math.py

Download Jupyter notebook: napari_img_math.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/napari/napari_parameter_sweep/","title":"napari parameter sweeps","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/napari/napari_parameter_sweep/#napari-parameter-sweeps","title":"napari parameter sweeps","text":"

napari is a fast, interactive, multi-dimensional image viewer for python. It uses Qt for the GUI, so it's easy to extend napari with small, composable widgets created with magicgui. Here, we demonstrate how to build a interactive widget that lets you immediately see the effect of changing one of the parameters of your function.

For napari-specific magicgui documentation, see the napari docs

See also: Some of this tutorial overlaps with topics covered in the napari image arithmetic example.

"},{"location":"generated_examples/napari/napari_parameter_sweep/#outline","title":"outline","text":"

This example demonstrates how to:

  1. Create a magicgui widget that can be used in another program (napari)

  2. Automatically call our function when a parameter changes

  3. Provide magicgui with a custom widget for a specific argument

  4. Use the choices option to create a dropdown

  5. Connect some event listeners to create interactivity.

"},{"location":"generated_examples/napari/napari_parameter_sweep/#code","title":"code","text":"

Code follows, with explanation below... You can also get this example at github.

import napari\nimport skimage.data\nimport skimage.filters\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\n# turn the gaussian blur function into a magicgui\n# - 'auto_call' tells magicgui to call the function when a parameter changes\n# - we use 'widget_type' to override the default \"float\" widget on sigma,\n#   and provide a maximum valid value.\n# - we contstrain the possible choices for 'mode'\n@magicgui(\n    auto_call=True,\n    sigma={\"widget_type\": \"FloatSlider\", \"max\": 6},\n    mode={\"choices\": [\"reflect\", \"constant\", \"nearest\", \"mirror\", \"wrap\"]},\n    layout=\"horizontal\",\n)\ndef gaussian_blur(layer: ImageData, sigma: float = 1.0, mode=\"nearest\") -> ImageData:\n    # Apply a gaussian blur to 'layer'.\n    if layer is not None:\n        return skimage.filters.gaussian(layer, sigma=sigma, mode=mode)\n\n# create a viewer and add some images\nviewer = napari.Viewer()\nviewer.add_image(skimage.data.astronaut().mean(-1), name=\"astronaut\")\nviewer.add_image(skimage.data.grass().astype(\"float\"), name=\"grass\")\n\n# Add it to the napari viewer\nviewer.window.add_dock_widget(gaussian_blur)\n# update the layer dropdown menu when the layer list changes\nviewer.layers.events.changed.connect(gaussian_blur.reset_choices)\n\nnapari.run()\n
"},{"location":"generated_examples/napari/napari_parameter_sweep/#walkthrough","title":"walkthrough","text":"

We're going to go a little out of order so that the other code makes more sense. Let's start with the actual function we'd like to write to apply a gaussian filter to an image.

"},{"location":"generated_examples/napari/napari_parameter_sweep/#the-function","title":"the function","text":"

Our function is a very thin wrapper around skimage.filters.gaussian. It takes a napari Image layer, a sigma to control the blur radius, and a mode that determines how edges are handled.

def gaussian_blur(\n    layer: Image, sigma: float = 1, mode=\"nearest\"\n) -> Image:\n    return filters.gaussian(layer.data, sigma=sigma, mode=mode)\n

The reasons we are wrapping it here are:

  1. filters.gaussian accepts a numpy array, but we want to work with napari layers that store the data in a layer.data attribute. So we need an adapter.
  2. We'd like to add some type annotations to the signature that were not provided by filters.gaussian
"},{"location":"generated_examples/napari/napari_parameter_sweep/#type-annotations","title":"type annotations","text":"

As described in the image arithmetic example, we take advantage of napari's built in support for magicgui by annotating our function parameters and return value as napari Layer types. napari will then tell magicgui what to do with them, creating a dropdown with a list of current layers for our layer parameter, and automatically adding the result of our function to the viewer when called.

For documentation on napari types with magicgui, see the napari docs

"},{"location":"generated_examples/napari/napari_parameter_sweep/#the-magic-part","title":"the magic part","text":"

Finally, we decorate the function with @magicgui and provide some options.

@magicgui(\n    auto_call=True,\n    sigma={\"widget_type\": \"FloatSlider\", \"max\": 6},\n    mode={\"choices\": [\"reflect\", \"constant\", \"nearest\", \"mirror\", \"wrap\"]},\n)\ndef gaussian_blur(\n  layer: ImageData, sigma: float = 1.0, mode=\"nearest\"\n) -> ImageData:\n    # Apply a gaussian blur to ``layer``.\n    if layer is not None:\n        return skimage.filters.gaussian(layer, sigma=sigma, mode=mode)\n
"},{"location":"generated_examples/napari/napari_parameter_sweep/#connecting-events","title":"connecting events","text":"

As described in the Events documentation, we can also connect any callback to the gaussian_blur.called signal that will receive the result of our decorated function anytime it is called.

def do_something_with_result(result):\n    ...\n\ngaussian_blur.called.connect(do_something_with_result)\n
"},{"location":"generated_examples/napari/napari_parameter_sweep/#code_1","title":"Code","text":"

Here's the full code example again.

import napari\nimport skimage.data\nimport skimage.filters\nfrom napari.types import ImageData\n\nfrom magicgui import magicgui\n\n\n# turn the gaussian blur function into a magicgui\n# - 'auto_call' tells magicgui to call the function when a parameter changes\n# - we use 'widget_type' to override the default \"float\" widget on sigma,\n#   and provide a maximum valid value.\n# - we contstrain the possible choices for 'mode'\n@magicgui(\n    auto_call=True,\n    sigma={\"widget_type\": \"FloatSlider\", \"max\": 6},\n    mode={\"choices\": [\"reflect\", \"constant\", \"nearest\", \"mirror\", \"wrap\"]},\n    layout=\"horizontal\",\n)\ndef gaussian_blur(layer: ImageData, sigma: float = 1.0, mode=\"nearest\") -> ImageData:\n    # Apply a gaussian blur to 'layer'.\n    if layer is not None:\n        return skimage.filters.gaussian(layer, sigma=sigma, mode=mode)\n\n\n# create a viewer and add some images\nviewer = napari.Viewer()\nviewer.add_image(skimage.data.astronaut().mean(-1), name=\"astronaut\")\nviewer.add_image(skimage.data.grass().astype(\"float\"), name=\"grass\")\n\n# Add it to the napari viewer\nviewer.window.add_dock_widget(gaussian_blur)\n# update the layer dropdown menu when the layer list changes\nviewer.layers.events.changed.connect(gaussian_blur.reset_choices)\n\nnapari.run()\n

Total running time of the script: ( 0 minutes 4.880 seconds)

Download Python source code: napari_parameter_sweep.py

Download Jupyter notebook: napari_parameter_sweep.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/notebooks/magicgui_jupyter/","title":"Jupyter notebooks and magicgui","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/notebooks/magicgui_jupyter/#jupyter-notebooks-and-magicgui","title":"Jupyter notebooks and magicgui","text":"

This example shows magicgui widgets embedded in a jupyter notebook.

The key function here is use_app(\"ipynb\").

You can also get this example at github.

import math\nfrom enum import Enum\n\nfrom magicgui import magicgui, use_app\nuse_app(\"ipynb\")\n\nclass Medium(Enum):\n    # Various media and their refractive indices.\n    Glass = 1.520\n    Oil = 1.515\n    Water = 1.333\n    Air = 1.0003\n\n\n@magicgui(\n    call_button=\"calculate\", result_widget=True, layout='vertical', auto_call=True\n)\ndef snells_law(aoi=1.0, n1=Medium.Glass, n2=Medium.Water, degrees=True):\n    # Calculate the angle of refraction given two media and an angle of incidence.\n    if degrees:\n        aoi = math.radians(aoi)\n    try:\n        n1 = n1.value\n        n2 = n2.value\n        result = math.asin(n1 * math.sin(aoi) / n2)\n        return round(math.degrees(result) if degrees else result, 2)\n    except ValueError:  # math domain error\n        return \"TIR!\"\n\n\nsnells_law\n

Total running time of the script: ( 0 minutes 0.000 seconds)

Download Python source code: magicgui_jupyter.py

Download Jupyter notebook: magicgui_jupyter.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/notebooks/mg_execution_times/","title":"Computation times","text":"

00:00.000 total execution time for generated_examples_notebooks files:

+-----------------------------------------------------------------------------------------+-----------+--------+ | magicgui_jupyter (docs/examples/notebooks/magicgui_jupyter.py) | 00:00.000 | 0.0 MB | +-----------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/progress_bars/mg_execution_times/","title":"Computation times","text":"

00:00.303 total execution time for generated_examples_progress_bars files:

+---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress_nested (docs/examples/progress_bars/progress_nested.py) | 00:00.101 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress_manual (docs/examples/progress_bars/progress_manual.py) | 00:00.077 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress (docs/examples/progress_bars/progress.py) | 00:00.072 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+ | progress_indeterminate (docs/examples/progress_bars/progress_indeterminate.py) | 00:00.053 | 0.0 MB | +---------------------------------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/progress_bars/progress/","title":"Simple progress bar","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress/#simple-progress-bar","title":"Simple progress bar","text":"

A simple progress bar demo with magicgui.

Out:

<FunctionGui long_running(steps=10, delay=0.1)>\n

from time import sleep\n\nfrom magicgui import magicgui\nfrom magicgui.tqdm import trange\n\n# if magicui.tqdm.tqdm or trange are used outside of a @magicgui function, (such as in\n# interactive use in IPython), then they fall back to the standard terminal output\n\n\n# If use inside of a magicgui-decorated function\n# a progress bar widget will be added to the magicgui container\n@magicgui(call_button=True, layout=\"horizontal\")\ndef long_running(steps=10, delay=0.1):\n    \"\"\"Long running computation with range iterator.\"\"\"\n    # trange(steps) is a shortcut for `tqdm(range(steps))`\n    for _i in trange(steps):\n        sleep(delay)\n\n\nlong_running.show(run=True)\n

Total running time of the script: ( 0 minutes 0.072 seconds)

Download Python source code: progress.py

Download Jupyter notebook: progress.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/progress_bars/progress_indeterminate/","title":"Indeterminate progress bar","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress_indeterminate/#indeterminate-progress-bar","title":"Indeterminate progress bar","text":"

Example of an indeterminate progress bar for a long running computation of unknown time.

Out:

<FunctionGui long_running(sleep_time=5)>\n

import time\n\nfrom superqt.utils import thread_worker\n\nfrom magicgui import magicgui\nfrom magicgui.tqdm import tqdm\n\n\n@magicgui(call_button=True, layout=\"horizontal\")\ndef long_running(sleep_time=5):\n    \"\"\"Long running computation with an indeterminate progress bar.\"\"\"\n    # Here tqdm is not provided an iterable argument, or the 'total' kwarg\n    # so it cannot calculate the expected number of iterations\n    # which means it will create an indeterminate progress bar\n    with tqdm() as pbar:\n        # It is best practice to use a separate thread for long running computations\n        # This makes the function non-blocking, you can still interact with the widget\n        @thread_worker(connect={\"finished\": lambda: pbar.progressbar.hide()})\n        def sleep(secs):\n            time.sleep(secs)\n\n        sleep(sleep_time)\n\n\nlong_running.show(run=True)\n

Total running time of the script: ( 0 minutes 0.053 seconds)

Download Python source code: progress_indeterminate.py

Download Jupyter notebook: progress_indeterminate.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/progress_bars/progress_manual/","title":"Manual progress bar","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress_manual/#manual-progress-bar","title":"Manual progress bar","text":"

Example of a progress bar being updated manually.

Out:

<FunctionGui manual(pbar: magicgui.widgets.ProgressBar = ProgressBar(value=<function match_type.<locals>.<lambda> at 0x142b1b6a0>, annotation=<class 'magicgui.widgets.ProgressBar'>, name='pbar'), increment: bool = 1)>\n

from magicgui import magicgui\nfrom magicgui.widgets import ProgressBar\n\n\n@magicgui(call_button=\"tick\", pbar={\"min\": 0, \"step\": 2, \"max\": 20, \"value\": 0})\ndef manual(pbar: ProgressBar, increment: bool = True):\n    \"\"\"Example of manual progress bar control.\"\"\"\n    if increment:\n        pbar.increment()\n    else:\n        pbar.decrement()\n\n\nmanual.show(run=True)\n

Total running time of the script: ( 0 minutes 0.077 seconds)

Download Python source code: progress_manual.py

Download Jupyter notebook: progress_manual.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/progress_bars/progress_nested/","title":"Nested progress bars","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/progress_bars/progress_nested/#nested-progress-bars","title":"Nested progress bars","text":"

Example using nested progress bars in magicgui.

Out:

<FunctionGui long_function(steps=10, repeats=4, choices='ABCDEFGHIJKLMNOP12345679', char='', delay=0.05)>\n

import random\nfrom time import sleep\n\nfrom magicgui import magicgui\nfrom magicgui.tqdm import tqdm, trange\n\n# if magicui.tqdm.tqdm or trange are used outside of a @magicgui function, (such as in\n# interactive use in IPython), then they fall back to the standard terminal output\n\n\n# If use inside of a magicgui-decorated function\n# a progress bar widget will be added to the magicgui container\n@magicgui(call_button=True, layout=\"vertical\")\ndef long_function(\n    steps=10, repeats=4, choices=\"ABCDEFGHIJKLMNOP12345679\", char=\"\", delay=0.05\n):\n    \"\"\"Long running computation with nested iterators.\"\"\"\n    # trange and tqdm accept all the kwargs from tqdm itself, as well as any\n    # valid kwargs for magicgui.widgets.ProgressBar, (such as \"label\")\n    for _r in trange(repeats, label=\"repeats\"):\n        letters = [random.choice(choices) for _ in range(steps)]\n        # `tqdm`, like `tqdm`, accepts any iterable\n        # this progress bar is nested and will be run & reset multiple times\n        for letter in tqdm(letters, label=\"steps\"):\n            long_function.char.value = letter\n            sleep(delay)\n\n\nlong_function.show(run=True)\n

Total running time of the script: ( 0 minutes 0.101 seconds)

Download Python source code: progress_nested.py

Download Jupyter notebook: progress_nested.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/under_the_hood/class_method/","title":"Deocrate class methods with magicgui","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/under_the_hood/class_method/#deocrate-class-methods-with-magicgui","title":"Deocrate class methods with magicgui","text":"

Demonstrates decorating a class method with magicgui.

Once the class is instantiated, instance.method_name will return a FunctionGui in which the instance will always be provided as the first argument (i.e. \"self\") when the FunctionGui or method is called.

Out:

instance: a, counter: 0.0, sigma: 0.0\ninstance: b, counter: 0.0, sigma: 0.0\n

from magicgui import event_loop, magicgui\nfrom magicgui.widgets import Container\n\n\nclass MyObject:\n    \"\"\"Example object class.\"\"\"\n\n    def __init__(self, name):\n        self.name = name\n        self.counter = 0.0\n\n    @magicgui(auto_call=True)\n    def method(self, sigma: float = 0):\n        \"\"\"Example class method.\"\"\"\n        print(f\"instance: {self.name}, counter: {self.counter}, sigma: {sigma}\")\n        self.counter = self.counter + sigma\n        return self.name\n\n\nwith event_loop():\n    a = MyObject(\"a\")\n    b = MyObject(\"b\")\n    container = Container(widgets=[a.method, b.method])\n    container.show()\n    assert a.method() == \"a\"\n    assert b.method() == \"b\"\n

Total running time of the script: ( 0 minutes 0.056 seconds)

Download Python source code: class_method.py

Download Jupyter notebook: class_method.ipynb

Gallery generated by mkdocs-gallery

"},{"location":"generated_examples/under_the_hood/mg_execution_times/","title":"Computation times","text":"

00:00.120 total execution time for generated_examples_under_the_hood files:

+----------------------------------------------------------------------------------------+-----------+--------+ | self_reference (docs/examples/under_the_hood/self_reference.py) | 00:00.064 | 0.0 MB | +----------------------------------------------------------------------------------------+-----------+--------+ | class_method (docs/examples/under_the_hood/class_method.py) | 00:00.056 | 0.0 MB | +----------------------------------------------------------------------------------------+-----------+--------+

"},{"location":"generated_examples/under_the_hood/self_reference/","title":"Self reference magicgui widgets","text":"

Note

Click here to download the full example code

"},{"location":"generated_examples/under_the_hood/self_reference/#self-reference-magicgui-widgets","title":"Self reference magicgui widgets","text":"

Widgets created with magicgui can reference themselves, and use the widget API.

Out:

<FunctionGui function(width=400, x: int = 50)>\n

from magicgui import magicgui\n\n\n@magicgui(auto_call=True, width={\"max\": 800, \"min\": 100}, x={\"widget_type\": \"Slider\"})\ndef function(width=400, x: int = 50):\n    \"\"\"Example function.\"\"\"\n    # the widget can reference itself, and use the widget API\n    function.x.width = width\n\n\nfunction.show(run=True)\n

Total running time of the script: ( 0 minutes 0.064 seconds)

Download Python source code: self_reference.py

Download Jupyter notebook: self_reference.ipynb

Gallery generated by mkdocs-gallery

"}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 4ed3a6ad2..2ce067e67 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ diff --git a/type_map/index.html b/type_map/index.html index e718d6c59..ca6f33bca 100644 --- a/type_map/index.html +++ b/type_map/index.html @@ -3162,7 +3162,7 @@

Default Type Mappingmagicgui.widgets.ProgressBar ProgressBar -{'bind': <function match_type.<locals>.<lambda> at 0x13b5ee3e0>, 'visible': True} +{'bind': <function match_type.<locals>.<lambda> at 0x13a9faa20>, 'visible': True} types.FunctionType