如果列表更改,Tkinter的OptionMenu回调将不起作用 [英] Tkinter's OptionMenu callback doesn't work if the list is changed
问题描述
每当我更改OptionMenu值时,回调都会平稳运行,但是当按下按钮时,我的代码要求更新列表(用于OptionMenu).当我查看它时,我唯一能找到的答案就是完全擦除OptionMenu,然后通过.add_command方法插入每个新值.简化的代码如下:
Whenever I change the OptionMenu value, the callback runs smoothly, but my code requires the list (that I use for the OptionMenu) to be updated, when a button is pressed. When I looked into it, the only answer I could find was to completly erase OptionMenu and then insert each new value through .add_command method. The simplified code is as follows:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
# list_of_files = [] is previously defined
def Change_selection_OptionMenu(event):
# Do some changes in the page
var = tk.StringVar(root)
style_optionMenu = ttk.Style()
style_optionMenu.configure('style_option.TMenubutton', background = mycolor, foreground = "white")
option_files = ttk.OptionMenu(root,var,list_of_files[0],*list_of_files, style = 'style_option.TMenubutton', command = Change_selection_OptionMenu )
option_files.config(width = 20)
option_files.grid(row=0,column=0)
tk.Button(master = root, text = "Button", commnad = lambda: button_sabe()).grid()
def button_save():
#Among other things
# ...
var.set('')
option_files['menu'].delete(0, 'end')
for choice in list_of_files:
option_files['menu'].add_command(label=choice,command = tk._setit(var, choice))
root.deiconify()
更改值列表后,回调将不再运行.我猜问题出在用于新类型选择的命令"中,但是我不知道如何处理它,以简单地更新列表,同时在选择一个选项时仍执行回调.有人可以帮忙吗?非常感谢你!
After changing the list of values, the callback doesn't run anymore. I guess the problem is in the "command" I use for the new type of choices, but I don't know how to deal with it, to simply update the list while still performing the callback when an option is selected. Anyone can help? Thank you very much!
推荐答案
tk._setit
接受三个参数:变量,值和选定时应执行的命令.因此,您需要添加第三个参数:
tk._setit
accepts three arguments: the variable, the value and the command that should be executed when selected. So you need to add that third argument:
option_files['menu'].add_command(label=choice,command = tk._setit(var, choice, Change_selection_OptionMenu))
这篇关于如果列表更改,Tkinter的OptionMenu回调将不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!