Changing the options of a OptionMenu when clicking a Button

前端 未结 3 2040
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 07:08

Say I have an option menu network_select that has a list of networks to connect to.

import Tkinter as tk

choices = (\'network one\', \'network          


        
相关标签:
3条回答
  • 2020-11-29 07:28

    I modified your script to demonstrate how to do this:

    import Tkinter as tk
    
    root = tk.Tk()
    choices = ('network one', 'network two', 'network three')
    var = tk.StringVar(root)
    
    def refresh():
        # Reset var and delete all old options
        var.set('')
        network_select['menu'].delete(0, 'end')
    
        # Insert list of new options (tk._setit hooks them up to var)
        new_choices = ('one', 'two', 'three')
        for choice in new_choices:
            network_select['menu'].add_command(label=choice, command=tk._setit(var, choice))
    
    network_select = tk.OptionMenu(root, var, *choices)
    network_select.grid()
    
    # I made this quick refresh button to demonstrate
    tk.Button(root, text='Refresh', command=refresh).grid()
    
    root.mainloop()
    

    As soon as you click the "Refresh" button, the options in network_select are cleared and the ones in new_choices are inserted.

    0 讨论(0)
  • 2020-11-29 07:32

    In case of using ttk, there is a convenient set_menu(default=None, values) method on the OptionMenu object.

    0 讨论(0)
  • 2020-11-29 07:41

    The same, but with tk.Menu widget:

    # Using lambda keyword and refresh function to create a dynamic menu.
    import tkinter as tk
    
    def show(x):
        """ Show menu items """
        var.set(x)
    
    def refresh(l):
        """ Refresh menu contents """
        var.set('')
        menu.delete(0, 'end')
        for i in l:
            menu.add_command(label=i, command=lambda x=i: show(x))
    
    root = tk.Tk()
    menubar = tk.Menu(root)
    root.configure(menu=menubar)
    menu = tk.Menu(menubar, tearoff=False)
    menubar.add_cascade(label='Choice', menu=menu)
    
    var = tk.StringVar()
    l = ['one', 'two', 'three']
    refresh(l)
    l = ['four', 'five', 'six', 'seven']
    tk.Button(root, text='Refresh', command=lambda: refresh(l)).pack()
    tk.Label(root, textvariable=var).pack()
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题