Python Tkinter 中的鼠标位置
pythontkinterserver side programmingprogramming
事件对于在大型应用程序中执行和管理多个任务非常有用。我们可以使用 bind(‘handler’, ‘callback’) 方法将特定事件与键盘按钮或鼠标按钮绑定。通常,跟踪鼠标指针及其运动是为了构建屏幕保护程序、2D 或 3D 游戏。为了打印指针的坐标,我们必须将 Motion 与回调函数绑定,该函数获取 x 和 y 变量中指针的位置。
示例
#导入 tkinter 库 from tkinter import * #创建 tkinter 框架或窗口的实例 win= Tk() #设置 tkinter 框架的几何形状 win.geometry("750x250") def callback(e): x= e.x y= e.y print("Pointer is current 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