gpt4 book ai didi

python - 如何从另一个线程更新 GUI?使用Python

转载 作者:行者123 更新时间:2023-12-01 09:05:43 25 4
gpt4 key购买 nike

从 python 中的另一个线程更新 gui 的最佳方法是什么。

我在thread1中有主函数(GUI),从这里我引用了另一个线程(thread2),是否可以在中工作时更新GUI >Thread2 而不取消 thread2 的工作,如果是的话我该怎么做?

有关线程处理的任何建议阅读内容。 ?

最佳答案

当然,您可以使用线程同时运行多个进程。

你必须创建一个像这样的类:

from threading import Thread

class Work(Thread):

def __init__(self):
Thread.__init__(self)
self.lock = threading.Lock()

def run(self): # This function launch the thread
(your code)

如果你想同时运行多个线程:

def foo():
i = 0
list = []
while i < 10:
list.append(Work())
list[i].start() # Start call run() method of the class above.
i += 1

如果您想在多个线程中使用同一个变量,请小心。您必须锁定此变量,以便它们不会同时到达此变量。像这样:

lock = threading.Lock()
lock.acquire()
try:
yourVariable += 1 # When you call lock.acquire() without arguments, block all variables until the lock is unlocked (lock.release()).
finally:
lock.release()

在主线程中,您可以在队列上调用 join() 来等待所有挂起的任务完成。

这种方法的优点是您无需创建和销毁线程,而这会带来很大的成本。工作线程将连续运行,但当队列中没有任务时将进入休眠状态,使用零 CPU 时间。

希望对你有帮助。

关于python - 如何从另一个线程更新 GUI?使用Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52073973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com