Tkinter Designer

← tkinter how-to

How do I get the selected value from a Combobox in tkinter?

A Combobox is a ttk widget, and .get() on the widget itself returns the current text — no variable required, though one still helps when several places need the value.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

colour = ttk.Combobox(root, values=["red", "green", "blue"], state="readonly")
colour.current(0)                 # show the first option
colour.pack()

def go():
    print("picked", colour.get())

tk.Button(root, text="Go", command=go).pack()
root.mainloop()

Why it starts empty

Passing values fills the drop-down but selects nothing, so the box comes up blank and .get() returns an empty string until someone chooses. Set a starting choice yourself with .current(0) for the first item, or .set("green") for a particular one.

colour.current(0)        # by position
colour.set("green")      # by value
colour.current()         # -> the index of the current value

People can type anything unless you stop them

A Combobox is editable by default: its state is normal, so the user can ignore your list entirely and type their own text, which .get() will hand straight back to you. Setting state="readonly" keeps the drop-down usable while making the text unmodifiable, and it is the right default for a fixed set of choices.

Leave it editable only when free text genuinely is allowed, and validate what comes back — a Combobox always returns a string, whatever the list looked like.

colour = ttk.Combobox(root, values=[...], state="readonly")

Reacting when they choose

The widget fires <<ComboboxSelected>> when a choice is made from the list. Bind that rather than polling, and read the value inside the handler — the handler takes the usual event argument.

def on_pick(event):
    print("now", colour.get())

colour.bind("<<ComboboxSelected>>", on_pick)

Changing the options later

The list is a normal widget option, so assigning to it replaces the choices at any time. Setting it does not clear the current text, which can leave a value on screen that is no longer in the list — clear it yourself when that matters.

colour["values"] = ["cyan", "magenta"]
colour.set("")           # clear a now-invalid selection

Doing it without the lookup

Type the options one per line in the inspector and the export builds the ttk.Combobox with them. Tick "Expose a variable" to get a StringVar as well, and pick <<ComboboxSelected>> from the events list to have the handler stub written for you.

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

Open the tkinter designer →

Related questions