首页 > 解决方案 > 线程无法加入 tkinter

问题描述

我正在构建 GUI 并遇到无法正确加入线程的问题。我提取了基本部分并编写了以下代码:启动线程的按钮和关闭线程的按钮。

import tkinter as tk
import threading
from time import sleep

class test:
    def __init__(self):
        root = tk.Tk()
        root.geometry('300x100')
        self.runAllflag = False
        tk.Button(root, text="run", command = self.run).pack()
        tk.Button(root, text="stop", command = self.stop).pack()
        self.status = tk.StringVar()
        tk.Label(root, textvariable = self.status).pack()
        root.mainloop()

    def test1(self):
        while self.runAllflag:
            sleep(0.1)
            print('threading runnning')
        else:
            print('Escaped from the loop') 
            self.status.set('Stopped')  #### Seems that the program stuck here ###
            print('Status written "Stopped')

    def run(self):
        if not self.runAllflag:
            self.runAllflag = True
            self.status.set('Running')
            self.t = threading.Thread(target=self.test1)
            self.t.start()

    def stop(self):
        if self.runAllflag:
            self.runAllflag = False
            self.t.join()

if __name__ == '__main__':
    test()

当我运行 GUI 时,单击运行按钮,然后单击停止按钮。这是消息日志:

threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
threading runnning
Escaped from the loop

似乎程序卡在了在函数中写入标签内容的行.test1(self)。我想知道它无法正确编写的原因是什么。

标签: pythonmultithreadingtkinter

解决方案


推荐阅读