简体   繁体   English

Tkinter 选项菜单

[英]Tkinter optionmenu

Is there a way to get the choice of an OptionMenu, without knowing the name of the StringVar the choice is saved in?有没有办法在不知道保存选择的 StringVar 的名称的情况下选择 OptionMenu?

I have an function that automatically creates more OptionMenu items, and gives their variable the same name.我有一个函数可以自动创建更多的 OptionMenu 项目,并为其变量提供相同的名称。 It also saves the OptionMenu object in a list:它还将 OptionMenu 对象保存在列表中:

def addInternalPartipantList():
    global coworkerDict
    global f

    choiceVar1 = StringVar(window)
    choiceVar1.set('Vælg medarbejder')
    coworkerChoice = OptionMenu(window, choiceVar1, *coworkerDict)
    f += 1
    coworkerChoice.grid(column = 2, row = f)
    chosenCoworkers.append(coworkerChoice)

Now can I do something like:现在我可以做这样的事情:

chosenCoworkers[0].getVar().get()

to get the chosen coworker in that specific OptionMenu?在特定的 OptionMenu 中获取所选同事?

or is there another way that I can specify which choiceVar1 it is that I want to get the value of?或者有没有另一种方法可以指定我想要获取哪个choiceVar1的值?

The function is called by a Button, if that has any relevance for the answer to this question该函数由按钮调用,如果这与此问题的答案有任何相关性

Here is a simple example of how you can check a value when someone selects the item.这是一个简单的示例,说明如何在有人选择项目时检查值。

When you use a command to reference a function in the OptionsMenu method the command will automatically pass the value selected as the event.当您使用命令引用 OptionsMenu 方法中的函数时,该命令将自动传递所选的值作为事件。 This way you can actually do something with that value without even knowing the StringVar.通过这种方式,您实际上可以在不知道 StringVar 的情况下使用该值执行某些操作。

import tkinter as tk

root = tk.Tk() 

def print_choice(event):
    print(choice_var.get()) # prints value based on choice var
    print(event)# prints selection directly from the event passed by the command in OptionMenu

working_list = ["Option 1", "Option 2", "Option 3", "Option 4"]
choice_var = tk.StringVar()
tk.OptionMenu(root, choice_var, *working_list, command=print_choice).pack()

root.mainloop()

Here is another example.这是另一个例子。 No mater how many OptionsMenu you create if you set the command to a function you can always get the value selected without knowing the StringVar.如果将命令设置为函数,则无论您创建多少个 OptionsMenu,您始终可以在不知道 StringVar 的情况下获得所选值。

import tkinter as tk

root = tk.Tk() 

def print_choice(event):
    print(event)# prints selection directly from the event passed by the command in OptionMenu

working_list = ["Option 1", "Option 2", "Option 3", "Option 4"]

for i in range(4):
    tk.OptionMenu(root, tk.StringVar(), *working_list, command=print_choice).pack()

root.mainloop()

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

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