我有一个问题,终止的while循环,这是通过线程选项启动。
stop变量的值为True和False。我应该通过线程启动停止选项吗?
完整的程序开始,一个循环开始,每秒打印一次TEST,点击STOP按钮,我什么也得不到!
我甚至认为我的停止是禁用时,循环正在进行中!
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()
使用STOP按钮停止循环!
1条答案
按热度按时间mfuanj7w1#
回答你的问题“我应该通过线程启动停止选项吗?“是的,我想你应该这样做,你已经快做完了!“!”只需要将“command = button_start_command”更改为“command = button_starter”,就可以在我的环境中工作!!