python - 线程无法加入 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)
。我想知道它无法正确编写的原因是什么。
解决方案
推荐阅读
- protocol-buffers - 定义一个依赖于枚举值的字段
- android - Android 上的 React Native:无法运行程序“节点”:错误 = 2,没有这样的文件或目录
- mysql - MySQL触发器为插入的行选择正确的值
- reactjs - 在回调函数中使用 setState 挂钩时反应过多的重新渲染
- java - Quartz 调度程序在集群模式下的所有节点上触发 cron 作业
- node.js - Express Validator 无法显示错误消息
- grouping - 使用 Power Query 对数据进行分组和转置
- javascript - 使用 JSON 数组值设置 css
- python - 将文本从文件复制到另一个文件并编辑生成的文件
- automation - 有没有办法将语音作为有效负载从 Alexa 发送到 Node-Red?