简体   繁体   English

有没有办法让 tkinter 的选项菜单等待用户选择?

[英]Is there a way to make tkinter's optionmenu to wait for the users choice?

Im trying to write a tkinter program that creates lots of new drop down lists and buttons depending on the user's choice.我正在尝试编写一个 tkinter 程序,该程序根据用户的选择创建许多新的下拉列表和按钮。 For example, a user chooses some option from a drop down list and another drop down list appears which depends on the the option that the user have chosen.例如,用户从下拉列表中选择某个选项,然后出现另一个下拉列表,这取决于用户选择的选项。 Im trying to use the users choice but as soon as the optionmenu drop down list appears, the code keeps running and doesn't wait for the user's choice, I would like to know how to make the program to wait for the user's choice.我试图使用用户的选择,但是一旦出现选项菜单下拉列表,代码就会继续运行并且不等待用户的选择,我想知道如何让程序等待用户的选择。 Furthermore, if a user chooses some option from the drop down list after he already chosen something, I would like to interact with his decision again.此外,如果用户在他已经选择了某些东西之后从下拉列表中选择了某个选项,我想再次与他的决定进行交互。 How can I do it?我该怎么做? I thought about using loops but then I wouldn't be able to proceed to the next operations.我考虑过使用循环,但后来我无法进行下一个操作。

I just created a sample work, may be use full to you我刚刚创建了一个示例作品,可能对你有用

# It will be main list
main_list = ['One', 'two', 'three', 'four']

# it will be second list
sub_list = {'One': [11, 12, 13, 14], 'two': [21, 22, 23, 24], 'three': [31, 32, 33, 34], 'four': [41, 42, 43, 44]}

# importing module
from tkinter import *

# creating a window
root = Tk()
# just creating a fixed window
root.geometry("500x500")

# variable for option menu one
Value1 = StringVar()

# just a default value
Value1.set('Select Options')

# variable for second menu
Value2 = StringVar()

# creating a second option ment but not placing
secondmenu = OptionMenu(root, Value2, 'select')


# this method is called for the first option menu
def get2ndOptions(event):
    # get the 2nd list for options menu
    select_values = sub_list[Value1.get()]
    
    # setting the variable for the default value
    Value2.set(select_values[0])
    
    # pack is called for placement
    secondmenu.pack(pady=20)

    # updating the 2nd menu list 
    secondmenu["menu"].delete(0, "end")
    for item in select_values:
        secondmenu["menu"].add_command(
            label=item,
            command=lambda value=item: Value2.set(value))

# 1st option menu is created
OptionMenu(root, Value1, *main_list, command=get2ndOptions).pack(pady=20)

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM