使用 tkinter 中的按钮启动/停止 while 循环

问题描述 投票:0回答:1

通过使用两个不同的按钮,我尝试基于扫描模式的 while 循环来启动和停止进程(实际上在本例中只是计数)。在下面的代码中,我尝试简化和概括我正在处理的实际项目中发生的更复杂的过程。运行代码可以看到,按下播放按钮即可开始计数;但是,当您按下停止按钮时,该过程不会立即停止。我之前曾设法使其按预期工作,但是在使用面向对象的方法重写代码时,一切都不再正常工作。目前,我无法理解问题是否出在 while 循环构造中,或者是否我以错误的方式使用线程。 任何建议都非常欢迎和赞赏!

from tkinter import *
import threading
import time

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(1))
        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(0))
        self.stop_button.pack()

    def process(self, trig):
        self.trig = trig

        while True:
            if self.trig == 1:

                for i in range (10):
                    time.sleep(0.5)
                    print (i)


            elif self.trig == 0:
                print ("stopped...")
                break

    def play(self, switch):


        self.switch = int(switch)
        t1 = threading.Thread (target = self.process, args = [self.switch], daemon = True)
        t1.start()
        

root = Tk()

app = gui(root)
root.mainloop()
python class user-interface tkinter while-loop
1个回答
1
投票

只需创建一个单独的线程来接收何时开始和停止倒计时的信号

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()

© www.soinside.com 2019 - 2024. All rights reserved.