如何在 Tkinter 中獲取可滾動畫布上的座標?
畫布小元件有兩個座標系統:(a) 視窗座標系統和 (b) 畫布座標系統。視窗座標系統總是從視窗中最左角(0,0)開始,而畫布座標系統指定了專案在畫布中的實際放置位置。
要將視窗座標系轉換成畫布座標系,我們可以使用以下兩種方法:
canvasx(event.x) canvas(event.y)
如果我們考慮視窗座標系的情況,那麼滑鼠事件只發生在視窗座標系中。我們可以將視窗座標轉換為畫布座標系。
示例
在這個應用程式中,我們將獲得畫布視窗中滑鼠指標的位置。
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Create a canvas widget
canvas = Canvas(win)
canvas.pack()
def on_button_pressed(event):
start_x = canvas.canvasx(event.x)
start_y = canvas.canvasy(event.y)
print("start_x, start_y =", start_x, start_y)
def on_button_motion(event):
end_x = canvas.canvasx(event.x)
end_y = canvas.canvasy(event.y)
print("end_x, end_y=", end_x, end_y)
# Bind the canvas with Mouse buttons
canvas.bind("<Button-1>", on_button_pressed)
canvas.bind("<Button1-Motion>", on_button_motion)
# Add a Label widget in the window
Label(win, text="Move the Mouse Pointer and click " "anywhere on the Canvas").pack()
win.mainloop()輸出
執行以上程式碼將顯示一個視窗。
如果我們移動滑鼠指標並在畫布上的任何位置單擊,它將在控制檯上列印指標的相對座標。
start_x, start_y = 340.0 159.0
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP