Reputation: 29
I'm trying to make a minesweeper game, and for that the user needs to be able to set flags. In every minesweeperr game, it works with right click. I tried googling and know how to get coordinates of my mouse cursor, but it works weirdly with buttons. Anywhere else, it gives normal coordinates, but when the cursor is over buttons, it gives me coordiantes between 10 and 30. Why is this? I place the buttons in a loop using .place()
.
Here's the code:
def rightclick(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Button-3>', rightclick)
When I'm not hovering over buttons, it returns normal coordinates like: 452, 539
and 311, 523
But when I am, it returns: 11, 16
and 30, 11
Can someone explain what is going on?
Upvotes: 1
Views: 470
Reputation: 5339
As @acw1668 writes in the comment section the event.x
and event.y
return the relative coordinates of Button
widget due to the inheritance.
You can get the coordinates of root with event.x_root
and event.y_root
methods and the event.widget
returns the widget where the trigger comes from.
Code:
"""
Example for root/relative mouse coordinates in Tkinter
"""
import tkinter
class App(tkinter.Tk):
"""
App class from tkinter.Tk
"""
def __init__(self):
super().__init__()
button_obj = tkinter.Button(width=10, height=10, background="black")
button_obj.pack(padx=10, pady=10)
button_obj.bind("<Button-3>", self.right_click)
@staticmethod
def right_click(event):
"""
Callback method for Right Click on mouse
Args:
event: Event object
Returns: None
"""
print("Coordinates on the button widget: {}, {}".format(event.x, event.y))
print("Coordinates on the root: {}, {}".format(event.x_root, event.y_root))
print("Triggered widget: {}\n".format(event.widget))
root = App()
root.mainloop()
GUI:
Console output after some right clicks:
>>> python3 test.py
Coordinates on the button widget: 18, 131
Coordinates on the root: 30, 223
Triggered widget: .!button
Coordinates on the button widget: 27, 57
Coordinates on the root: 39, 149
Triggered widget: .!button
Coordinates on the button widget: 64, 68
Coordinates on the root: 76, 160
Triggered widget: .!button
Coordinates on the button widget: 67, 118
Coordinates on the root: 79, 210
Triggered widget: .!button
Upvotes: 1