PySimpleGUI - Slider Element



The Slider widget comprises of a horizontal or vertical bar over which a slider button can be moved across with the help of mouse. The length of the bar indicates a range of a numerical parameter (such as font size, length/width of a rectangle etc.). The manual movement of the slider button changes the instantaneous value of the parameter, which can be further used in the program.

The object of Slider class is declared as follows −

PySimpleGUI.Slider(range, default_value, resolution, orientation, tick_interval)

These parameters are specific to the Slider control. The description of these parameters is given below −

  • range − The slider's bar represents this range (min value, max value)

  • default_value − starting value to which the slider button is set in the beginning

  • resolution − the smallest amount by which the value changes when the slider is moved

  • tick_interval − The frequency of a visible tick should be shown next to slider

  • orientation − either 'horizontal' or 'vertical'

  • disable_number_display − if True no number will be displayed by the Slider Element

Other attributes inherited from the Element class, such as color, size, font etc can be used to further customize the Slider object.

The update() method of the Slider class helps in refreshing the following parameters of the Slider object −

  • value − sets current slider value

  • range − Sets a new range for slider

the following code generates a PysimpleGUI window showing a Text Label with Hello World caption. There is a horizontal slider whose value changes from 10 to 30. Its key parameter is "-SL-".

Whenever the slider button is moved across, the "-SL-" event occurs. The instantaneous value of the slider button is used as the font size and the Text caption is refreshed.

import PySimpleGUI as psg
layout = [
   [psg.Text('Hello World', enable_events=True,
   key='-TEXT-', font=('Arial Bold', 20),
   size=(50, 2), relief="raised", border_width=5,
   expand_x=True, justification='center')],

   [psg.Slider(range=(10, 30), default_value=12,
   expand_x=True, enable_events=True,
   orientation='horizontal', key='-SL-')]
]
window = psg.Window('Hello', layout, size=(715, 150))
while True:
   event, values = window.read()
   print(event, values)
   if event == psg.WIN_CLOSED or event == 'Exit':
      break
   if event == '-SL-':
      window['-TEXT-'].update(font=('Arial Bold', int(values['-SL-'])))
window.close()

Save and run the above code. As you move the slider button, the font size of the Hello World text keeps changing. The output window will appear as follows −

Slider Element
pysimplegui_element_class.htm
Advertisements