Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

python - Changing the options of a OptionMenu when clicking a Button

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 two', 'network three')
var = tk.StringVar(root)
network_select = tk.OptionMenu(root, var, *choices)

Now, when the user presses the refresh button, I want to update the list of networks that the user can connect to.

  • I don't I can use .config because I looked through network_select.config() and didn't see an entry that looked like the choices I gave it.
  • I don't think this is something one can change using a tk variable, because there is no such thing as a ListVar.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...