Search code examples
pythonformstkintertkinter-entry

Entry selection list with tkinter


How can I generate a normal selection list (like the "State" field in any HTML form for postal addresses) using Python tkinter? As illustrated below, the Listbox widget displays all the selections in a large box all the time, and if you reduce the height to 1, it does not expand the list when selected. The OptionMenu widget pops up the list correctly when selected, but doesn't display the current value in an Entry-like box when closed. And the Entry widget has the desired appearance but doesn't have an associated list of values.

Please don't tell me that tkinter can't do a basic form selection :-(.

from tkinter import *

class App:
    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        items = ["Apple", "Banana", "Cherry"]
        self.list = Listbox(frame, width=8, height=1)
        for item in items:
            self.list.insert(END, item)
        self.list.pack(side=LEFT)

        fruit = StringVar()
        fruit.set(items[1])
        self.menu = OptionMenu(frame, fruit, *items)
        self.menu.pack(side=LEFT)

        self.entry = Entry(frame, width=8)
        self.entry.insert(0, items[2])
        self.entry.pack(side=LEFT)

root = Tk()
app = App(root)
root.mainloop()

Solution

  • You're looking for a combo box widget, TTK provides this widget:

    http://docs.python.org/dev/library/tkinter.ttk.html

    http://www.tkdocs.com/widgets/combobox.html