如何从 Tkinter 中的列表创建下拉菜单? [英] How can I create a dropdown menu from a List in Tkinter?

查看:39
本文介绍了如何从 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(),在下面的情况下,这是 variable:


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.

这篇关于如何从 Tkinter 中的列表创建下拉菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆