当我简单地使用 tkinter
时,该程序按预期工作的小部件。当我使用 ttk
的小部件程序会重复两次。我尝试了我所知的几乎所有方法来解决这个问题,我相信 *args
有关系。有什么办法可以防止我的function
从运行两次?
from tkinter import *
from tkinter import ttk
root = Tk()
first = StringVar(root)
second = StringVar(root)
Ore = {'Options': [''], 'Yes': ['One'], 'No': ['Two']}
entry1 = ttk.OptionMenu(root, first, *Ore.keys())
entry2 = ttk.OptionMenu(root, second, '')
entry1.pack()
entry2.pack()
def _up_options(*args):
print('update_options')
ores = Ore[first.get()]
second.set(ores[0])
menu = entry2['menu']
menu.delete(0, 'end')
for line in ores:
print('for')
menu.add_command(label=line, command=lambda choice=line: second.set(choice))
first.trace('w', _up_options)
root.mainloop()
PS,我推了
*args
在我的工作中。如果有人可以解释这一点,我将不胜感激
最佳答案
我想我想通了。问题是该变量实际上由 ttk OptionMenu 设置了两次。
看一下 tkinter OptionMenu 中的这段代码:
for v in values:
menu.add_command(label=v, command=_setit(variable, v, callback))
这会为每个值在菜单中添加一个按钮,带有
_setit
命令。当_setit
被调用它设置变量和另一个回调(如果提供):def __call__(self, *args):
self.__var.set(self.__value)
if self.__callback:
self.__callback(self.__value, *args)
现在看一下 ttk OptionMenu 中的这段代码:
for val in values:
menu.add_radiobutton(label=val,
command=tkinter._setit(self._variable, val, self._callback),
variable=self._variable)
而不是
command
这增加了一个 radiobutton
到菜单。所有单选按钮都通过将它们链接到相同的变量来“分组”。因为单选按钮有一个变量,当单击其中一个时,该变量将设置为按钮的值。在此旁边,添加了与 tkinter OptionMenu 中相同的命令。如上所述,这会设置变量,然后触发另一个命令提供。如您所见,现在变量更新了两次,一次是因为它链接到单选按钮,另一次是因为它设置在 _setit
中。功能。因为您跟踪变量的变化并且该变量设置了两次,所以您的代码也运行了两次。因为变量在 ttk 代码中设置了两次,我想你对此无能为力。如果您不从 OptionMenu 以外的任何其他代码部分更改变量,您可以选择不跟踪该变量,而是将您的函数添加为
command
到选项菜单:entry1 = ttk.OptionMenu(root, first, *Ore.keys(), command=_up_options)
附言这是由 this commit 引入的之后 this bugreport .
我想在添加
variable=self._variable
时该命令应该已更改为仅 command=self._callback
.
关于python-3.x - 当使用 ttk 小部件时,tkinter 函数会重复两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171384/