Tkinter Designer

← tkinter how-to

How do I use a Spinbox in tkinter?

Set the range with from_ and to — note the trailing underscore, because from is a Python keyword — and read the current value with .get(), remembering that what comes back is text.

import tkinter as tk

root = tk.Tk()

qty = tk.Spinbox(root, from_=1, to=10)
qty.pack()

def order():
    n = int(qty.get())        # .get() returns a string, always
    print("ordering", n)

tk.Button(root, text="Order", command=order).pack()
root.mainloop()

The value is a string even when it looks like a number

.get() returns text whatever the range is, so arithmetic on it either fails with a TypeError or, worse, silently concatenates. Convert at the point you read it. This stays true when the Spinbox is backed by an IntVar: the variable gives you an integer, but the widget still hands out a string.

int(qty.get()) + 1      # 2
qty.get() + 1           # TypeError

count = tk.IntVar(value=5)
tk.Spinbox(root, from_=0, to=10, textvariable=count)
count.get() + 1         # 6 — the variable is typed

Steps other than one

increment sets how far each arrow click moves, and it works with decimals as well as whole numbers. Combine it with a format when you want the display padded, because a float can otherwise show more digits than you intended.

tk.Spinbox(root, from_=0, to=1, increment=0.1)

Spinning through words

Pass values instead of a range and the arrows step through your list in order. The widget still returns a string, which in this case is exactly what you want, and the first entry shows on startup rather than leaving the field blank.

tk.Spinbox(root, values=("low", "medium", "high"))

Typing is still allowed

The arrows constrain what they produce, but the field itself is an entry: someone can type 999 into a Spinbox that goes up to 10, and .get() will return it. Check the value when you read it, or attach validation, rather than trusting the range to enforce itself.

Doing it without the lookup

Set the range in the inspector and the export writes from_, to and any increment. Tick "Expose a variable" for an IntVar when you want the value typed on the way out — the conversion trap above is the one thing a designer cannot do for you, because only you know whether the field is a count or a label.

Lay the window out visually and read the generated Python as you go.

Open the tkinter designer →

Related questions