Tkinter's OptionMenu callback doesn't work if the list is changed

三世轮回 提交于 2019-12-11 08:13:19

问题


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!


回答1:


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))


来源:https://stackoverflow.com/questions/51514209/tkinters-optionmenu-callback-doesnt-work-if-the-list-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!