使用tkinter制作条目选择列表

1 投票
2 回答
7733 浏览
提问于 2025-04-17 02:50

我想知道怎么用Python的tkinter库生成一个普通的选择列表,就像在任何HTML表单中的“州”字段那样。下面的例子中,Listbox这个控件会一直在一个大框里显示所有的选项,如果把高度调到1,它在选中时不会展开列表。而OptionMenu这个控件在选中时会正确弹出列表,但关闭时不会在像输入框那样显示当前的值。Entry控件看起来是我想要的样子,但它没有关联的选项列表。

请不要告诉我tkinter不能做基本的表单选择 :-(。

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()

2 个回答

1

你问的这个东西叫做下拉框(combobox)。如果你用的是旧版本的Python(小于2.7),可以使用 tix.ComboBox。如果你用的是Python 2.7或更新的版本,可以使用 ttk.combobox(这个链接指向的是最新的Python 3.x文档,但它和Python 2.7中的控件是一样的)。

2

你在找一个组合框的控件,TTK提供了这个控件:

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

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

撰写回答