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

查看:238
本文介绍了如何在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.

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

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