Python Tkinter 中的滑鼠位置


在大型應用程式中,“事件”非常有助於執行和管理多項任務。我們可以使用 bind('handler', 'callback') 方法將特定事件與鍵盤按鈕或滑鼠按鈕繫結在一起。為了構建螢幕保護程式、2D 或 3D 遊戲,通常會追蹤滑鼠指標及其運動。為了列印指標的座標,我們必須將 Motion 與一個回撥函式繫結在一起,該回調函式獲取指標在 xy 變數中的位置。

示例

#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
def callback(e):
   x= e.x
   y= e.y
   print("Pointer is currently at %d, %d" %(x,y))
win.bind('<Motion>',callback)
win.mainloop()

輸出

執行以上程式碼,只要我們在視窗上懸停,就會列印指標的實際位置。

在控制檯中,當你在螢幕上移動滑鼠時,將看到滑鼠指標的實際位置。

Pointer is currently at 452, 225
Pointer is currently at 426, 200
Pointer is currently at 409, 187
Pointer is currently at 392, 174
Pointer is currently at 382, 168
Pointer is currently at 378, 163
Pointer is currently at 376, 159
Pointer is currently at 369, 150
Pointer is currently at 366, 141
Pointer is currently at 362, 130

更新於:2021-4-22

8K+ 次瀏覽

開始您的 職業生涯

透過完成課程來獲得認證

開始
廣告