【发布时间】:2020-05-07 09:50:22
【问题描述】:
我有 tkinter 应用程序,它可以控制以及从串行连接导入值。我需要两个独立运行的循环,一个用于串行连接,一个用于 tkinter 的主要应用程序。
我尝试通过使用线程来做到这一点,来自此链接中的答案: Running infinite loops using threads in python 但 tkinter 应用程序运行速度非常慢。 我的代码看起来像这样。
import tkinter as tk
from threading import Thread
class Tkinter_Window(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start()
def run(self):
self.tkinter_window = tk.Tk()
self.tkinter_window.mainloop()
class Serial_Connection(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start()
def run(self):
#serial connection should go here#
pass
class Some_Other_Process(Thread):
def __init__(self):
Thread.__init__(self)
self.daemon = True
self.start()
def run(self):
#any other needed processes#
pass
if __name__ == "__main__":
Tkinter_Window()
Serial_Connection()
Some_Other_Process()
while True:
pass
但是 tkinter 应用程序太慢了。在寻找我读到多处理在我的情况下可能会更好地工作的原因之后。我很欣赏有关如何运行并行进程同时能够优化它们所占用的处理能力的任何意见。
我也尝试了多处理 https://docs.python.org/2/library/multiprocessing.html,但我不知道如何运行主 tkinter 应用程序的循环。
【问题讨论】:
-
你不应该在子线程中运行
tkinter。在主线程中运行。
标签: python-3.x multithreading tkinter multiprocessing