Python GUI 保持卡住等待线程代码完成运行

标签 python multithreading

我有一个 python GUI 程序,它需要执行相同的任务但有多个线程。问题是我调用了线程,但它们不是并行执行而是顺序执行。第一个执行,它结束然后第二个,等等。我希望他们独立开始。

主要组成部分有:
1.菜单(查看)
2. ProcesStarter( Controller )
3.进程( Controller )

菜单 是您点击“开始”按钮的地方,该按钮调用ProcesStarter 中的函数。

ProcesStarter 创建Process 对象和线程,并在for 循环中启动所有线程。

菜单:

class VotingFrame(BaseFrame):

  def create_widgets(self):
    self.start_process = tk.Button(root, text="Start Process", command=lambda: self.start_process())
    self.start_process.grid(row=3,column=0, sticky=tk.W)

  def start_process(self):
    procesor = XProcesStarter()
    procesor_thread = Thread(target=procesor.start_process())
    procesor_thread.start()

ProcesStarter:

class XProcesStarter:

   def start_process(self):
       print "starting new process..."

       # thread count
       thread_count = self.get_thread_count()

       # initialize Process objects with data, and start threads
       for i in range(thread_count):
          vote_process = XProcess(self.get_proxy_list(), self.get_url())
          t = Thread(target=vote_process.start_process())
          t.start()

过程:

class XProcess():

    def __init__(self, proxy_list, url, browser_show=False):
        # init code

    def start_process(self):
        # code for process

当我按下“启动进程”的 GUI 按钮时,GUI 被锁定,直到两个线程都完成执行。 这个想法是线程应该在后台工作并并行工作。

最佳答案

在将它指定为线程的目标时立即调用 procesor.start_process():

#use this
procesor_thread = Thread(target=procesor.start_process)

#not this
procesor_thread = Thread(target=procesor.start_process())
                          # this is called right away ^

如果您立即调用它,它会返回 None,这是 Thread 的有效目标(它什么都不做),这就是为什么它按顺序发生,线程什么都不做。

关于Python GUI 保持卡住等待线程代码完成运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36230333/

相关文章:

python - 如何动态链接 Pyspark 中的条件?

python - 南方迁移和 django 迁移有什么区别?

Python队列组合

c# - String 类中的线程安全

java - Java中的读/写锁实现

linux - C++11中的并发问题

python - 文件名(来自多个文件)作为一个数据框中的列名

python - 在 Python 中测试类的正确方法是什么?

python - 从多个 Excel 文件创建 Pandas 数据框

multithreading - 具有容器管理事务和工作线程的 MDB