In this example, we’ll demonstrate how to add a Spinbox widget in a Tkinter window. A Spinbox allows users to select a value from a defined range by either clicking the up or down arrows or entering a number manually.
Python Code: Adding a Spinbox
First, we create a basic Tkinter window and add a Spinbox widget named 'spin'
. We set the range of the Spinbox from 0 to 10.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | from tkinter import * root = Tk() root.title("App") root.geometry("200x100") spin = Spinbox( from_=0, to=10, width=10 ).pack() root.mainloop() |
Output:
Python Code: Displaying Spinbox Value in a Label with Button Click
Now, we will enhance the example by adding a button. When the button is clicked, the value selected in the Spinbox will be displayed in a Label widget.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | from tkinter import * root = Tk() root.title("App") root.geometry("200x100") spinValue = StringVar() def message(): label["text"] = spinValue.get() spin = Spinbox( from_=0, to=10, width=10, textvariable=spinValue, ).pack() button = Button( text="Click!", command=message ) button.pack() label = Label( text="..." ) label.pack() root.mainloop() |
Output:
This code introduces a StringVar
to hold the value of the Spinbox, and a button that updates the Label with the current value of the Spinbox when clicked.