我正在尝试使用Python和tkinter编写此简单代码。每次我启动程序时,tkinter窗口都会正确弹出,如果我按“播放”,则循环开始。但是在那之后,如果我想使用“停止”按钮停止该过程,则程序没有响应。我认为我应该使用多进程或多线程,因为当周期开始时,接口无法正常工作。
我是Python的开始,所以请对我理解:D
我在Google上进行了搜索,但是发现的所有内容太复杂了,有人可以通过简单的方式解释该怎么做吗?
from pynput.keyboard import Key, Controller as KeyboardController
from pynput.mouse import Button, Controller as MouseController
import time
import random
import string
import tkinter as tk
window = tk.Tk()
window.geometry("600x600")
window.title("Test")
window.resizable(False,False)
def arresta_programma():
avvia_programma.destroy()
def avvia_programma():
r = 0
n = 0
l = 0
d = 0
while n < 1000 :
keyboard= KeyboardController()
keyboard.press('1')
keyboard.release('1')
time.sleep(random.randint(1,2))
keyboard.press('1')
keyboard.release('1')
r = random.randint(1,4)
if r == 1 and l <= 2:
keyboard= KeyboardController()
time.sleep(random.randint(1,2))
keyboard.press(Key.left)
time.sleep(random.randint(0,1))
keyboard.release(Key.left)
n = n + 1
l = l + 1
d = d - 1
first_button = tk.Button(text = "Play" , command = avvia_programma)
first_button.grid(row = 5, column = 5)
first_button = tk.Button(text = "Stop" , command = arresta_programma)
first_button.grid(row = 6, column = 6)
if __name__ == "__main__":
window.mainloop()
即使用户按下“播放”按钮,我也希望程序做出响应。我还希望通过“停止”按钮打开界面,并准备再次按下“播放”。
答案 0 :(得分:0)
正如您所说,至少应使用线程。您不能在您的代码(在本例中为tkinter处理)的mainLoop中使用time.sleep。大量的睡眠和循环会阻塞您的循环,并使其崩溃。
我建议创建一个从threading.Thread继承的类。下面的“播放”示例。
from threading import Thread
def execute_avvia():
job = AvviaProgramma()
job.setDaemon(True)
job.start()
class AvviaProgramma(Thread):
def __init__(self, *args, **kwargs):
super(AvviaProgramma, self).__init__(*args, **kwargs)
self.n = 0
self.r = 0
self.l = 0
self.d = 0
def run(self):
while self.n < 1000:
print(self.n)
keyboard = KeyboardController()
keyboard.press('1')
keyboard.release('1')
time.sleep(random.randint(1,2))
keyboard.press('1')
keyboard.release('1')
r = random.randint(1, 4)
if r == 1 and self.l <= 2:
keyboard = KeyboardController()
time.sleep(random.randint(1, 2))
keyboard.press(Key.left)
time.sleep(random.randint(0, 1))
keyboard.release(Key.left)
self.n = self.n + 1
self.l = self.l + 1
self.d = self.d - 1
first_button = tk.Button(text = "Play", command=execute_avvia)
first_button.grid(row = 5, column = 5)
如您所见,我在类方法的run()中关闭了while循环,该循环取自Thread。这个解决方案并不完美,但是我希望对于初学者来说足够清楚。
祝你好运!