我在终止通过线程选项启动的 while 循环时遇到问题。
stop 变量的值为 True 和 False。我应该通过线程启动“停止”选项吗?
完整的程序启动,启动一个循环,每秒打印单词“TEST”,单击“停止”按钮我什么也没得到!
我什至认为循环进行时我的停止被禁用!
import tkinter as tk
import threading
import time
class App(tk.Tk):
def __init__(self):
super().__init__()
global stop
stop = False
# If the STOP button is pressed then terminate the loop
def button_stop_command():
global stop
stop = True
# Start loop
def button_start_command():
global stop
stop = False
while stop == False:
print("TEST")
time.sleep(1)
# Button starter with thread
def button_starter():
t = threading.Thread(target=button_start_command)
t.start()
# self windows size
window_width = 1024
window_height = 600
# get the screen dimension
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
# find the center point
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)
# set the position of the window to the center of the screen
self.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
# Resize main window xy, on/off, 0 or 1 .
self.resizable(0, 0)
# Main window on top of stack.
self.attributes('-topmost', 1)
# Windows transparency.
self.attributes('-alpha', 1)
# Button START
# self.button = tk.Button(self, text='START', width = 20, height = 10, command = self.button_clicked)
self.button = tk.Button(self, text='START', width = 20, height = 10, command = button_start_command)
self.button.place(x = 600, y = 350)
# Button STOP
# self.button = tk.Button(self, text='START', width = 20, height = 10, command = self.button_clicked)
self.button_stop = tk.Button(self, text='STOP', width = 20, height = 10, command = button_stop_command)
self.button_stop.place(x = 800, y = 350)
if __name__ == "__main__":
app = App()
app.mainloop()
使用“停止”按钮停止循环!
回答您的问题“我应该通过线程启动停止选项吗?”是“是的,我想你应该这样做。你已经快完成了!!” 只需将“command=button_start_command”更改为“command=button_starter”,这在我的环境中有效!!