通过使用两个不同的按钮,我试图启动和停止一个基于while循环的进程,该循环扫描整个模式(在本例中实际上只是计数)。在下面的代码中,我试图简化和概括我正在处理的实际项目中发生的更复杂的过程。正如您通过运行代码所看到的,您可以通过按play按钮来开始计数;但是,当您按下stop按钮时,该过程并不会立即停止。
只需创建一个单独的线程,该线程接收何时开始和停止倒计时的信号.
from tkinter import *
import threading
import time
should_run = False
class a:
def __init__(self):
while True:
if should_run:
for i in range(10):
if not should_run:
print('Stopped...')
break
if should_run:
time.sleep(0.5)
print(i)
t1 = threading.Thread(target=a,daemon=True)
t1.start()
class gui:
def __init__(self, window):
# play button
self.play_frame = Frame(master=window, relief=FLAT, borderwidth=1)
self.play_frame.grid(row=0, column=0, padx=1, pady=1)
self.play_button = Button(self.play_frame, text="play", fg="blue", command=lambda: self.play(True))
self.play_button.pack()
# stop button
self.stop_frame = Frame(master=window, relief=FLAT, borderwidth=1)
self.stop_frame.grid(row=0, column=2, padx=1, pady=1)
self.stop_button = Button(self.stop_frame, text="stop", fg="red", command=lambda: self.play(False))
self.stop_button.pack()
def play(self, switch):
global should_run
should_run = switch
root = Tk()
app = gui(root)
root.mainloop()
标签:yyds,play,tkinter,self,stop,should,干货,frame,button
From: https://blog.51cto.com/u_15452495/6176576