我在 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()
不,我想要列印滑鼠相對于紅框的正確坐標。但是,當我將滑鼠懸停在按鈕上時,坐標會發生變化,并且不再代表紅色 window_frame 中的真實坐標。
有人有解決方案嗎?
uj5u.com熱心網友回復:
Motion與 Root 與其他小部件系結:
在試驗了你的代碼之后,我做了以下觀察:
- 當
Motion事件系結到根時,(event.x, event.y)回傳視窗中任何像素相對于該像素所在的視窗小部件的坐標。對應小部件(not )的左上角root取為 (0, 0)。 - 如果將
Motion事件系結到特定小部件,則僅當像素直接(event.x, event.y)存在于小部件內部時才回傳像素的坐標(相對于小部件)。如果將滑鼠懸停在子小部件上,則不會列印任何內容。
解決方案:
(event.x, event.y)現在,遇到您的問題,當滑鼠懸停在按鈕上時,您無法直接計算畫布坐標。您必須進行以下轉換。
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/452599.html
