Python 如何从 Tkinter 中的列表创建下拉菜单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45441885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:02:08  来源:igfitidea点击:

How can I create a dropdown menu from a List in Tkinter?

pythondrop-down-menutkinter

提问by Ethan Field

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.

我正在创建一个 GUI 来构建关于一个人的信息。我希望用户使用下拉栏选择他们的出生月份,之前将月份配置为列表格式。

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?

如何创建下拉列表以显示月份?

回答by Ethan Field

To create a "drop down menu" you can use OptionMenuin tkinter

要创建可以OptionMenu在 tkinter 中使用的“下拉菜单”

Example of a basic OptionMenu:

一个基本的例子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.

更多信息(包括上面的脚本)可以在这里找到。



Creating an OptionMenuof the months from a list would be as simple as:

OptionMenu从列表中创建一个月份将非常简单:

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


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:

为了检索用户选择的值,您可以简单地.get()在我们分配给小部件的变量上使用 a ,在以下情况下,这是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()

I would highly recommend reading through this sitefor further basic tkinter information as the above examples are modified from that site.

我强烈建议通读本网站以获取更多基本的 tkinter 信息,因为上述示例是从该网站修改而来的。