I have a slight problem in my code. I need a popup menu on my interface, that pops up, not when the right mouse button is pressed, but when a button (tkinter widget) is clicked.
An Example would be this: http://effbot.org/zone/tkinter-popup-menu.htm
However, instead of the event coordinates, I want to create the popupmenu at the same coordinates as the button.
self.popup_menu.tk_popup(x_button, y_button, 0)
The problem is that, when I move my interface window or scroll the scollbar (I have one in my interface) and click on the button again, the popupmenu is created not at the exact position where the button is. It seems that .tk_popup is only taking the window coordinates rather than the canvas coordinates.
Does someone know a solution?
EDIT: Here is a example:
from Tkinter import *
root = Tk()
popup = Menu(root, tearoff=0)
popup.add_command(label="Main Product")
popup.add_command(label="Side Product")
def popupm(x, y):
try:
popup.tk_popup(x, y, 0)
finally:
popup.grab_release()
x = 10
y = 15
bt = Button(root, text='Menu', command= lambda: popupm(x , y))
bt.place(x = 10, y = 15)
root.mainloop()
Greetings!
Buttons have a couple methods that give you what you want: .winfo_rootx() and .winfo_rooty() Here is a working example:
from Tkinter import *
root = Tk()
popup = Menu(root, tearoff=0)
popup.add_command(label="Main Product")
popup.add_command(label="Side Product")
def popupm(bt):
try:
x = bt.winfo_rootx()
y = bt.winfo_rooty()
popup.tk_popup(x, y, 0)
finally:
popup.grab_release()
bt = Button(root, text='Menu')
bt.configure(command = lambda: popupm(bt))
bt.place(x = 10, y = 15)
root.mainloop()
I tested it in python3, sorry if it doesn't translate to 2. Let us know if you have any troubles with it or need help adapting it a bit.