我還在學習使用 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 視窗并且我不知道為什么,否則坐標不會繼續更新。
發個截圖希望對你有幫助。
任何幫助表示贊賞。


uj5u.com熱心網友回復:
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497222.html
上一篇:OR3比較的簡單方法?
