即时更新 ttk.OptionMenu 而不影响其先前的回调/命令 [英] Update on the fly a ttk.OptionMenu without affecting its previous callback/command

查看:26
本文介绍了即时更新 ttk.OptionMenu 而不影响其先前的回调/命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个带有不同 ttk.OptionMenu 小部件的大型 GUI,这些小部件需要经常根据与用户的交互进行更新.每次用户从菜单中选择另一个值时,小部件都会通过命令输入进行函数回调.该命令工作正常,直到我需要更新 OptionMenu 小部件中的可能值.使用 add_command 更新后,我之前的回调不再起作用.

I am doing a large GUI with different ttk.OptionMenu widgets that need to be updated often depending on the interaction with the user. Each time the user selects another value from the menu, there is a function callback by the widget via the command input. The command works fine until I need to update the possible values within the OptionMenu widget. After updating using add_command, my previous callback does not work anymore.

有没有办法在不影响其原始回调的情况下更新 ttk.OptionMenu 的可能输入?让我举一个虚拟的例子来说明我的问题.我的原始代码就像

Is there any way of updating the possible inputs of a ttk.OptionMenu without affecting its original callback? Let me put a dummy example to illustrate my problem. My original code would be like

from tkinter import *
from tkinter import filedialog, messagebox, ttk

        
def printing(variable,*args):
    
    print('ok')
      
    if variable: 
        print(variable)

root=Tk()
List=['Madrid', 'Paris', 'Brussels']
variable = StringVar()

optionmenu = ttk.OptionMenu(root,variable,'', *List,
                            command=printing) 
optionmenu.pack()      
root.mainloop() 

然后用户将动态更新列表,菜单需要动态更新,使用:

Then the user would update the list dynamically, and the menu needs to be updated on the fly, using:

newList = ['Madrid', 'Paris', 'Brussels', 'London']
menu = optionmenu["menu"]
menu.delete(0, "end")
for string in newlist:
    menu.add_command(label=string,
                      command=lambda value=string: variable.set(value))

但是执行此操作后,回调printing 将不再起作用.同样重要的是,在一个选项中单击它应该成为 OptionMenu 显示的值(因此 StringVar 变量被设置为该输入)

but doing this operation, the callback printing would not work anymore. Also important to mention that one clicked in one option it should become the value showed by the OptionMenu ( so the StringVar variable is settled to that input)

我希望它很清楚

推荐答案

tkinter 模块中有一个内部类 _setitOptionMenu 在内部填充值.您可以按如下方式使用此类:

There is an internal class _setit in tkinter module which is used by OptionMenu internally to populate the values. You can use this class as below:

from tkinter import filedialog, messagebox, ttk, _setit
...

for value in newList:
    menu.add_command(label=value, command=_setit(variable, value, printing))

这篇关于即时更新 ttk.OptionMenu 而不影响其先前的回调/命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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