Debian Codegraph @

examples/03-widgets/checkbox_widget.py

raw
1 """
2 .. _checkbox_widget_example:
3
4 Checkbox Widget
5 ~~~~~~~~~~~~~~~
6
7 Use a checkbox to turn on/off the visibility of meshes in a scene.
8
9 See :func:`pyvista.Plotter.add_checkbox_button_widget` for more details.
10
11 """
12
13 # sphinx_gallery_thumbnail_number = 2
14 # sphinx_gallery_start_ignore
15 # widgets do not work in interactive examples
16 PYVISTA_GALLERY_FORCE_STATIC_IN_DOCUMENT = True
17 # sphinx_gallery_end_ignore
18
19 import pyvista as pv
20
21 # %%
22 # Single Checkbox
23 # +++++++++++++++
24
25 mesh = pv.Sphere()
26
27 pl = pv.Plotter()
28 actor = pl.add_mesh(mesh)
29
30
31 def toggle_vis(flag):
32 actor.SetVisibility(flag)
33
34
35 pl.add_checkbox_button_widget(toggle_vis, value=True)
36 pl.show()
37
38 # %%
39 # Multiple Checkboxes
40 # +++++++++++++++++++
41 #
42 # In this example, we will add many meshes to a scene with unique colors and
43 # create corresponding checkboxes for those meshes of the same color to toggle
44 # their visibility in the scene.
45
46 colors = [
47 ['ff0000', '28e5da', '0000ff'],
48 ['ffff00', 'c8bebe', 'f79292'],
49 ['fffff0', 'f18c1d', '23dcaa'],
50 ['d785ec', '9d5b13', 'e4e0b1'],
51 ['894509', 'af45f5', 'fff000'],
52 ]
53
54
55 class SetVisibilityCallback:
56 """Helper callback to keep a reference to the actor being modified."""
57
58 def __init__(self, actor):
59 self.actor = actor
60
61 def __call__(self, state):
62 self.actor.SetVisibility(state)
63
64
65 # %%
66
67 # Widget size
68 size = 50
69
70 pl = pv.Plotter()
71
72 Startpos = 12
73 for i, lst in enumerate(colors):
74 for j, color in enumerate(lst):
75 actor = pl.add_mesh(pv.Sphere(center=(i, j, 0)), color=color)
76 # Make a separate callback for each widget
77 callback = SetVisibilityCallback(actor)
78 pl.add_checkbox_button_widget(
79 callback,
80 value=True,
81 position=(5.0, Startpos),
82 size=size,
83 border_size=1,
84 color_on=color,
85 color_off='grey',
86 background_color='grey',
87 )
88 Startpos = Startpos + size + (size // 10)
89
90 pl.show()
91 # %%
92 # .. tags:: widgets