SpinButton¶
A Gtk.SpinButton
is an ideal way to allow the user to set the value of
some attribute. Rather than having to directly type a number into a
Gtk.Entry
, Gtk.SpinButton
allows the user to click on one of
two arrows to increment or decrement the displayed value. A value can still be
typed in, with the bonus that it can be checked to ensure it is in a given range.
The main properties of a Gtk.SpinButton
are set through
Gtk.Adjustment
.
To change the value that Gtk.SpinButton
is showing, use
Gtk.SpinButton.props.value
. The value entered can either be an integer
or float, depending on your requirements, use
Gtk.SpinButton.get_value_as_int()
or Gtk.SpinButton.get_value()
,
respectively.
When you allow the displaying of float values in the spin button, you may wish
to adjust the number of decimal spaces displayed by calling
Gtk.SpinButton.props.digits
.
By default, Gtk.SpinButton
accepts textual data. If you wish to limit
this to numerical values only, set Gtk.SpinButton.props.numeric
to True
.
We can also adjust the update policy of Gtk.SpinButton
. There are two
options here; by default the spin button updates the value even if the data
entered is invalid. Alternatively, we can set the policy to only update when the
value entered is valid by changing Gtk.SpinButton.props.update_policy
to
Gtk.SpinButtonUpdatePolicy.IF_VALID
.
Example¶
![../../../_images/spinbutton.png](../../../_images/spinbutton.png)
1import gi
2
3gi.require_version('Gtk', '4.0')
4from gi.repository import Gtk
5
6
7class SpinButtonWindow(Gtk.ApplicationWindow):
8 def __init__(self, **kargs):
9 super().__init__(**kargs, title='SpinButton Demo')
10
11 hbox = Gtk.Box(spacing=6)
12 self.set_child(hbox)
13
14 adjustment = Gtk.Adjustment(
15 upper=100, step_increment=1, page_increment=10
16 )
17 self.spinbutton = Gtk.SpinButton()
18 self.spinbutton.props.adjustment = adjustment
19 self.spinbutton.connect('value-changed', self.on_value_changed)
20 hbox.append(self.spinbutton)
21
22 check_numeric = Gtk.CheckButton(label='Numeric')
23 check_numeric.connect('toggled', self.on_numeric_toggled)
24 hbox.append(check_numeric)
25
26 check_ifvalid = Gtk.CheckButton(label='If Valid')
27 check_ifvalid.connect('toggled', self.on_ifvalid_toggled)
28 hbox.append(check_ifvalid)
29
30 def on_value_changed(self, _scroll):
31 print(self.spinbutton.get_value_as_int())
32
33 def on_numeric_toggled(self, button):
34 self.spinbutton.props.numeric = button.props.active
35
36 def on_ifvalid_toggled(self, button):
37 if button.get_active():
38 policy = Gtk.SpinButtonUpdatePolicy.IF_VALID
39 else:
40 policy = Gtk.SpinButtonUpdatePolicy.ALWAYS
41 self.spinbutton.props.update_policy = policy
42
43
44def on_activate(app):
45 win = SpinButtonWindow(application=app)
46 win.present()
47
48
49app = Gtk.Application(application_id='com.example.App')
50app.connect('activate', on_activate)
51
52app.run(None)