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.p开发者_StackOverflow中文版ack(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()
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
What you are asking for is called a combobox. If you are using an old version of python (<2.7) you can use tix.ComboBox. For python 2.7 and beyond you can use ttk.combobox (link points to latest python 3.x documentation, but it is the same widget as in python 2.7).
精彩评论