Issue
Lets assume i have an simple list as follow:
import tkinter as tk
root = tk.Tk()
root.geometry("300x400")
menubar = tk.Menu(root)
menu1 = tk.Menu(menubar, tearoff=0)
menu1.add_command(label="Button1")
menu1.add_command(label="Button2")
menubar.add_cascade(label='Menu1', menu=menu1)
tk.Tk.config(root, menu=menubar)
root.mainloop()
Can i add two different functionalities to Button1
and Button2
that are triggered when they are clicked on without using menu1.add_command(label="Button1", command=func1)
and menu1.add_command(label="Button2", command=func2)
?
Preferably, I am looking for some solution somehow doing something like these hypothetical solutions:
def func1():
pass
def func2():
pass
def binding(Menu1):
Menu1.Button1.bind(func1)
Menu1.Button2.bind(func2)
or
def handler(event):
if event = button1:
func1()
if event = button2:
func2()
menu1.bind(<clicked>, handler)
Solution
You can use the label of the menu item to get the index of it in the menu and then use menu1.entryconfig()
to bind a function on that menu item:
def binding(menu, label, func):
for i in range(menu.index("end")+1):
if menu.entrycget(i, "label") == label:
menu.entryconfigure(i, command=func)
return
binding(menu1, "Button1", func1)
binding(menu1, "Button2", func2)
Answered By - acw1668
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.