我試圖創建一個滑鼠回圈程式,我可以讓開始按鈕在回圈中作業,但是結束按鈕似乎會使tkinter崩潰,而不是關閉程式。
如果您有任何建議,我們將不勝感激
。import pyautogui
from tkinter import *
import sys
window = Tk()
def start_loop() 。
while True:
pyautogui.moveTo(3131, 891, 1)
pyautogui.PAUSE = 180 180.
pyautogui.moveTo(3128, 434, 1)
b1 = Button(window, text="啟動滑鼠", command=start_loop)
b1.grid(row=0, column=0)
def end_loop()。
print(sys.exit())
b2 = Button(window, text="Stop Mouse"/span>, command=end_loop)
b2.grid(row=0, column=1)
window.mainloop()
uj5u.com熱心網友回復:
你應該使用after函式
在tkinter中,它應該用回圈(我指的是mainloop)檢查介面的每個組件。
然而,如果你使用while True:,那么GUI就不能檢查關于其他函式或介面的反應,比如Button。
因此,你的程式可能會癱瘓。
import pyautogui
from tkinter import *
import sys
window = Tk()
def start_loop()。
pyautogui.moveTo(3131, 891, 1)
pyautogui.PAUSE = 1.8.
pyautogui.moveTo(3128, 434, 1)
window.after(180, start_loop) //after(ms_for_delay, function)
b1 = Button(window, text="啟動滑鼠", command=start_loop)
b1.grid(row=0, column=0)
def end_loop()。
sys.exit()
b2 = Button(window, text="Stop Mouse"/span>, command=end_loop)
b2.grid(row=0, column=1)
window.mainloop()
試試這個代碼。
uj5u.com熱心網友回復:
這也可以使用執行緒來實作。
它將消耗更多的資源,但我認為它的最終結果將不那么 "笨重"。
我添加了關于時間的評論和一些列印陳述句來跟蹤正在發生的事情:
我添加了關于時間的評論和一些列印陳述句來跟蹤正在發生的事情:
import pyautogui
from tkinter import *
import執行緒
import sys
import time
window = Tk()
t = False[/span
def start_thread()。
""啟動滑鼠執行緒""。
global t
if t:
return
t = threading.Thread(target = start_loop)
setattr(t, "flag", False)
t.start()
print("Mouse thread Started")
def start_loop()。
""移動滑鼠的回圈""/span>
t = threading.current_thread()
time.sleep(0.1) # 只是為了更好地列印。
while True:
print("Mouse thread Running")
pyautogui.moveTo(3131, 891, 1)
# 不確定你是想把pyautogui的時間調整為180,還是直接等待180秒。
#pyautogui.PAUSE = 180
for x in range(180)。
time.sleep(1)
flag = getattr(t, "flag")
if flag:
print("Mouse thread Stopped")
return(span class="hljs-string">"滑鼠執行緒停止")
pyautogui.moveTo(3128, 434, 1)
def end_loop()。
""結束滑鼠的回圈""
global t
if not t:
return not t.
setattr(t, "flag", True)
while t.is_alive()。
time.sleep(0.1)
t = 假的。
b1 = Button(window, text="Start Mouse", command=start_thread)
b1.grid(row=0, column=0)
b2 = Button(window, text="停止滑鼠", command=end_loop)
b2.grid(row=0, column=1)
window.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330576.html
標籤:
