0
votes

I'm trying to get the mouse position while pressing a button, but instead of getting the position of the mouse on Tkinter root, it gives me the position of the mouse on the button. For example, if the button is placed on 200, 200, and I press the top left of the button, it prints 0, 0 instead of 200, 200.

import Tkinter as tk

def leftclick(event):
    print("left")
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

root = tk.Tk()
add_user = tk.Button(root, height=63, width=195 ,text="sign up a user")
add_user.place(x= 20, y = 30)
root.bind("<Button-1>", leftclick)
root.mainloop()

1
what do you mean? - Sagi Levy
i added a minimal code to show how I get the mouse's position - Sagi Levy
missing (event) in definition. - Flob
thanks, ofcourse I have it coded. forgot to type it here. - Sagi Levy
the error has to be somewhere else. When i use leftclick exactly like you posted it, just adding print(x, y)at the end, and creatig a simple window with a button, it prints the window coordinates, not the button coordinates. - Flob

1 Answers

1
votes

You can call the winfo_pointerx and winfo_pointery methods of a widget to get each individual coordinate, or you can call winfo_pointerxy to get them both:

def leftclick(event):
    x, y = event.widget.winfo_pointerxy()
    print('{}, {}'.format(x, y))