I need a context menu to know the widget that called it, and then pass that value to its associated commands.
The only way I've achieved it is by using a global variable.
import tkinter as tk
class Example:
def __init__(self, window):
base = tk.Frame(window).pack()
for i in range(3):
l = tk.Label(base, text='label '+str(i))
l.pack()
l.bind("<Button-1>", lambda event: self.handler(event))
self.menu = tk.Menu(window, tearoff=0)
self.menu.add_command(label='test', command=self.test)
def handler(self, event):
self.menu.post(event.x_root, event.y_root)
self.menu.focus_set()
global widget
widget = event.widget
def test(self):
print ('click on widget: ', widget)
main = tk.Tk()
example = Example(main)
main.mainloop()
Is there another best practice to do this? If possible, without using global variables.