简体   繁体   中英

python tkinter mouse position “bind('<Motion>')” return wrong position

The problem is when the cursor is over one of these widgets Listbox , Label , Text the position becomes wrong

Right position

Wrong position

from tkinter import *
root = Tk()
root.geometry('250x250')
position = Label(root)
position.place(relx = 0.25, rely = 0.25)
listbox = Listbox(root)
listbox.place(relx = .5, rely = .5, relwidth = .5, relheight = .5)
root.bind('<Motion>', lambda e : position.config(text = f'({e.x},{e.y})'))
root.mainloop()

The position is relative to the widget, not the window. When your mouse moves over the listbox, the event goes to the listbox rather than the root window.

If you want the coordinates relative to the window, use e.x_root and e.y_root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM