如何在Tkinter中的列表中创建下拉菜单?
我正在创建一个用于构建有关一个人的信息的GUI。我希望用户使用一个下拉栏选择他们的出生月份,并将之前的月份配置为列表格式。
I am creating a GUI that builds information about a person. I want the user to select their birth month using a drop down bar, with the months configured earlier as a list format.
from tkinter import *
birth_month = [
'Jan',
'Feb',
'March',
'April'
] #etc
def click():
entered_text = entry.get()
Data = Tk()
Data.title('Data') #Title
label = Label(Data, text='Birth month select:')
label.grid(row=2, column=0, sticky=W) #Select title
如何创建一个下拉列表来显示月份?
How can I create a drop down list to display the months?
要创建一个下拉列表下拉菜单,则可以在tkinter中使用 OptionMenu
To create a "drop down menu" you can use OptionMenu
in tkinter
OptionMenu基本示例
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
更多信息(包括股票)可以在此处找到。
More information (including the script above) can be found here.
从列表中创建月份的 OptionMenu
很简单:
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
要检索用户选择的值,您可以简单地使用 .get()
分配给小部件的变量,在以下情况下,这是变量
:
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
我强烈建议您阅读此站点,以获得更多的基本tkinter信息,因为从该站点修改了上述示例。
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.