【发布时间】:2018-12-12 07:20:18
【问题描述】:
我正在尝试学习 python。但是我的线程有问题。首先我在“Proces”类中失败了,因为我把循环放在了错误的地方,我的程序更新从另一个类返回。
但现在我认为一切都是正确的,但它仍然不起作用。 我需要一个 GUI,我希望能够通过文本条目编写我的条件,并且我需要另一个类“Proces”来做一些事情,不断地或在指定的时间间隔检查互联网的状态等等。 .
问题是我的 tkinter GUI 在按下某些东西后冻结了
这是我的 GUI.py 文件:
import tkinter as tk
from Proces import Proces
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame, text="QUIT", fg="red",command=quit).pack(side=tk.LEFT)
pr = Proces()
print("\nGUI: proces init...")
pr.start()
print("\nGUI: Start ended")
root.mainloop()
这是 Proces.py 文件:
import time, threading
class Proces(threading.Thread):
def loop(self):
while True:
time.sleep(2)
print("\nProces: looping")
def __init__(self):
threading.Thread.__init__(self)
print("\nProces: Starting proces")
time.sleep(2)
def run(self):
self.deamon = True
print("\nProces: Starting loop")
self.loop()
*这是输出:*
Proces: Starting proces
GUI: proces init...
Proces: Starting loop
GUI: Start ended
Proces: looping
Proces: looping
Proces: looping
Proces: looping
*但是tkinter的GUI没有反应。*
我应该如何做这样的任务? 感谢您的帮助、建议和回答
【问题讨论】:
-
你的
Proces.__init__为什么要睡2秒?这个睡眠是在主线程上,所以停止渲染 GUI 直到它结束? -
Proces类中有错字,应该是self.daemon = True,而不是self.deamon = True。 -
@JamesKent 睡眠只是因为我还在学习,只是为了测试延迟线程
-
@j_4321 我没有注意到守护进程拼写错误。但我想知道为什么另一个线程没有以第一个线程结束。谢谢
标签: python multithreading tkinter