繁体   English   中英

使用 Tkinter 绘制和跟踪鼠标指针

[英]Using Tkinter to draw and track a mouse pointer

我还在学习使用 Python 和 Tkinter。 我创建了一些代码(我认为)应该创建一个带有 2 个点的画布,然后连续打印鼠标光标的位置

    from tkinter import *
from win32 import win32gui
win = Tk()

def mouse_pos():
    flags, hcursor, (x, y) = win32gui.GetCursorInfo()
    return {"x": x, "y": y}

win.geometry("1500x900")
win.configure(background="black")

g_circle = Canvas(win, width=100, height=100, bg="black", bd=1, highlightthickness=0)
g_circle.place(x=100, y=100, in_=win)
g_circle.create_oval(50, 50, 100, 100, fill="green", offset="200,200", outline="white")

b_circle = Canvas(win, width=100, height=100, bg="black", bd=1, highlightthickness=0)
b_circle.place(x=1300, y=700, in_=win)
b_circle.create_oval(50, 50, 100, 100, fill="blue", outline="white")


while True:
    print(mouse_pos())
    win.mainloop()

我知道有一个无限循环,但我现在只是在测试它。

这个问题是,当我运行此代码时,会打开一个带有 2 个圆圈的画布的 TK 窗口,然后一个 cmd 会在文本中显示 x 和 y 坐标的单个值。 除非我关闭 TK 窗口并且我不知道为什么,否则坐标不会继续更新。

发个截图希望对你有帮助。

任何帮助表示赞赏。

打开的两个窗口

带有鼠标光标位置的cmd

win.mainloop()将阻塞 while 循环,直到主窗口关闭。

您可以使用.after()替换 while 循环:

...
def mouse_pos():
    # no need to use external module to get the mouse position
    #flags, hcursor, (x, y) = win32gui.GetCursorInfo()
    x, y = win.winfo_pointerxy()
    print({"x": x, "y": y})
    # run mouse_pos() again 10 microseconds later
    win.after(10, mouse_pos)
...
''' don't need the while loop
while True:
    print(mouse_pos())
    win.mainloop()
'''
# start the "after loop"
mouse_pos()
win.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM