GUI Slider#

Screen shot of a GUI slider in the example
gui_slider.py#
 1"""
 2GUI Slider Example
 3
 4If Python and Arcade are installed, this example can be run from the
 5command line with:
 6python -m arcade.examples.view_screens_minimal
 7
 8This example demonstrates how to create a GUI slider and react to
 9changes in its value.
10
11There are two other ways of handling update events. For more
12information on this subject, see the gui_flat_button example.
13
14If Python and Arcade are installed, this example can be run from the command line with:
15python -m arcade.examples.gui_slider
16"""
17from __future__ import annotations
18
19import arcade
20from arcade.gui import UIManager, UILabel
21from arcade.gui.events import UIOnChangeEvent
22from arcade.gui.widgets.slider import UISlider
23
24
25class MyView(arcade.View):
26    def __init__(self):
27        super().__init__()
28        # Required, create a UI manager to handle all UI widgets
29        self.ui = UIManager()
30
31        # Create our pair of widgets
32        ui_slider = UISlider(value=50, width=300, height=50)
33        label = UILabel(text=f"{ui_slider.value:02.0f}")
34
35        # Change the label's text whenever the slider is dragged
36        # See the gui_flat_button example for more information.
37        @ui_slider.event()
38        def on_change(event: UIOnChangeEvent):
39            label.text = f"{ui_slider.value:02.0f}"
40            label.fit_content()
41
42        # Create a layout to hold the label and the slider
43        ui_anchor_layout = arcade.gui.widgets.layout.UIAnchorLayout()
44        ui_anchor_layout.add(
45            child=ui_slider,
46            anchor_x="center_x",
47            anchor_y="center_y"
48        )
49        ui_anchor_layout.add(child=label, align_y=50)
50
51        self.ui.add(ui_anchor_layout)
52
53    def on_show_view(self):
54        self.window.background_color = arcade.color.DARK_BLUE_GRAY
55        # Enable UIManager when view is shown to catch window events
56        self.ui.enable()
57
58    def on_hide_view(self):
59        # Disable UIManager when view gets inactive
60        self.ui.disable()
61
62    def on_draw(self):
63        self.clear()
64        self.ui.draw()
65
66
67if __name__ == '__main__':
68    window = arcade.Window(800, 600, "UIExample", resizable=True)
69    window.show_view(MyView())
70    window.run()