In this wxPython article we want to learn about How to Create Slider in wxPython, sliders are an important graphical user interface (GUI) element that allows users to select a value from a range of possible values. they are commonly used in applications like media players, image editors and data visualization tools.
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import wx class SliderFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, title="GeeksCoders - Slider Example", size=(300, 200)) panel = wx.Panel(self) self.slider = wx.Slider(panel, -1, 50, 0, 100, (10, 10), (250, -1), wx.SL_HORIZONTAL) self.slider.Bind(wx.EVT_SCROLL, self.on_slider_scroll) self.slider_value = wx.StaticText(panel, label="50", pos=(130, 50)) def on_slider_scroll(self, event): value = self.slider.GetValue() self.slider_value.SetLabel(str(value)) if __name__ == '__main__': app = wx.App() frame = SliderFrame(None) frame.Show(True) app.MainLoop() |
In the above code first we have imported our module.
1 |
import wx |
The next step is to create a slider using wx.Slider class. slider constructor takes several arguments, including the parent window, slider ID, initial value, minimum value, maximum value and the position and size of the slider on the screen.
1 |
self.slider = wx.Slider(panel, -1, 50, 0, 100, (10, 10), (250, -1), wx.SL_HORIZONTAL) |
The final step is to respond to events generated by the slider. slider generates events when the user moves the slider, either by dragging the slider thumb or by clicking on the slider track. for responding to these events we need to bind an event handler function to the slider.
1 |
self.slider.Bind(wx.EVT_SCROLL, self.on_slider_scroll) |
In here we are binding on_slider_scroll function to the wx.EVT_SCROLL event. this function will be called whenever the user moves the slider.
The on_slider_scroll function might look something like this, this function retrieves the current value of the slider and prints it in wxPython label.
1 2 3 |
def on_slider_scroll(self, event): value = self.slider.GetValue() self.slider_value.SetLabel(str(value)) |
Run the complete code and this will be the result
Learn More on wxPython
- How to Create wxPython Main Window wx.Frame
- How to Create wxPython Panel with wx.Panel
- How to Create wxPython Button
- How to Create wxPython Text Control
- How to Create wxPython Static Text
- How to Create wxPython CheckBox
- How to Create wxPython RadioButton
- How to Create List Box in wxPython
- How to Create ComboBox in wxPython