提问人:marestudio 提问时间:9/21/2023 最后编辑:Christoph Rackwitzmarestudio 更新时间:10/1/2023 访问量:48
Tkinter - 带按钮的循环启动/停止 - 螺纹选项
Tkinter - Loop Start/Stop with button - threading option
问:
我对通过线程选项启动的 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按钮的停止循环!
答:
0赞
Akasama
9/28/2023
#1
您的问题“我应该通过线程启动停止选项吗?”的答案是“是的,我认为你应该。你差不多完成了!!
只有改变,这在我的环境中工作!command = button_start_command
command = button_starter
评论
button_starter
button_start_command