Reputation: 25
My very first tkinter experience was going rather smoothly, but now I'm stumped.
I grabbed some code I saw on another thread, and added a 'New Item'. I can see that the callback function isn't executed when 'New Item' is selected. StrVar isn't updated for 'New Item' as it is for the initial items. If StrVar did update, then I wouldn't need the callback function.
I have tried to resolve this using .__setit(), .trace_add(), callback functions, as well as some .configure stuff. What am I missing? I need for the user to be able to see the item they selected.
import tkinter as tk
def callback(selection):
print(selection)
root = tk.Tk()
options = tk.StringVar()
menu = tk.OptionMenu(root, options, 'a', 'b', 'c', command=callback)
menu.pack()
menu['menu'].add_command(label='New Item')
options.set('a')
root.mainloop()
Upvotes: 0
Views: 460
Reputation: 855
You need to assign the command for every option you add. Additionally, you need to add options.set(selection)
at the end to make sure the "New Item" options is selected.
Code:
import tkinter as tk
def callback(selection):
print(selection)
options.set(selection)
root = tk.Tk()
options = tk.StringVar()
menu = tk.OptionMenu(root, options, 'a', 'b', 'c', command=callback)
menu.pack()
menu['menu'].add_command(label='New Item', command=lambda: callback('New Item'))
options.set('a')
root.mainloop()
Upvotes: 1