[英]Tkinter mouse pointer not working for hovering over button
我的鼠標指針有問題 Python Tkinter。
我有以下代碼:
import tkinter as tk
root = tk.Tk()
def motion(event):
x, y = window_canvas.canvasx(event.x), window_canvas.canvasy(event.y)
print('{}, {}'.format(x, y))
window_canvas = tk.Canvas(root, borderwidth=0, background="white", width = 300, height = 300, highlightthickness=0)
window_canvas.pack(fill='both')
window_frame = tk.Frame(window_canvas, background='red', borderwidth=0, width = 300, height = 300)
window_frame.pack()
button = tk.Button(window_frame, text=' ', borderwidth=1, highlightbackground='#9c9c9c', bg='black')
button.place(x=50, y=50)
root.bind('<Motion>', motion)
root.mainloop()
不,我想要打印出我的鼠標相對於紅框的正確坐標。 但是,當我 hover 在按鈕上時,坐標會發生變化,不再根據紅色 window_frame 表示真實坐標。
有人有解決辦法嗎?
Motion
與 Root 與其他小部件進行綁定:在試驗了您的代碼之后,我做出了以下觀察:
Motion
事件綁定到root時, (event.x, event.y)
返回window中任意一個像素相對於該像素所在widget的坐標。 相應小部件(不是root
)的左上角被視為 (0, 0)。Motion
事件綁定到特定的小部件, (event.x, event.y)
) 僅當像素直接存在於小部件內時才返回像素的坐標(相對於小部件)。 如果您 hover 將鼠標懸停在子部件上,則不會打印任何內容。 現在,來到你的問題,當鼠標懸停在按鈕上時,你不能直接從(event.x, event.y)
計算 canvas 坐標。 您將必須進行以下轉換。
window_coords = topleft_button_coordinates + (event.x, event.y)
canvas_coords = canvas.canvasx(window_coords.x), canvas.canvasy(window_coords.y)
僅當坐標是相對於按鈕時,才必須執行上述轉換。 您可以使用event.widget
屬性來檢查事件是否由按鈕觸發。
可以使用.winfo_x()
和.winfo_y()
。
工作代碼:
import tkinter as tk
root = tk.Tk()
def motion(event):
global button
convx, convy = event.x, event.y
if event.widget == button:
convx, convy = button.winfo_x() + event.x, button.winfo_y() + event.y
x, y = window_canvas.canvasx(convx), window_canvas.canvasy(convy)
print('{}, {}'.format(x, y))
window_canvas = tk.Canvas(root, borderwidth=0, background="white", width = 300, height = 300, highlightthickness=0)
window_canvas.pack(fill='both')
window_frame = tk.Frame(window_canvas, background='red', borderwidth=0, width = 300, height = 300)
window_frame.pack()
button = tk.Button(window_frame, text=' ', borderwidth=1, highlightbackground='#9c9c9c', bg='black')
button.place(x=50, y=50)
root.bind('<Motion>', motion)
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.