Skip to main content
 首页 » 编程设计

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

2025年05月04日27oomusou

我有一个 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 的有效目标(它什么都不做),这就是为什么它按顺序发生,线程什么都不做。