2017-09-01 53 views
0

我已經編寫了一個程序,它循環執行一些給定的文件(實際上是電影文件),搜索該文件的字幕並下載它。這是一個wxPython GUI應用程序。現在,每次下載字幕時,我想用一些文本更新GUI的ListControl。代碼如下:用於更新wxPython GUI的thread.join()的任何替代方法?

for i in range(total_items): 
    path = self.list.GetItem(i, 0) # gets the item (first column) from list control 
    path = path.GetText() # contains the path of the movie file 

    t = Thread(target = self.Downloader, args = (path,)) 
    t.start() 

    t.join() # using this hangs the GUI and it can't be updated 
    self.list.SetItem(i, 1, 'OK') # update the listcontrol for each download 

很明顯,我只想在線程完成時更新GUI。我使用了t.join(),但後來才明白它不能用於更新GUI,如此問題中所述:GObject.idle_add(), thread.join() and my program hangs

現在,我想使用類似的問題,但我不能在我使用wxPython的時候找出任何東西。

回答

1

要使用wx.CallAfter從你的線程內,將使用主線程調用無論你將它傳遞

def Downloader(a_listbox,item_index): 
    path = a_listbox.GetItem(item_index, 0) # gets the item (first column) from list control 
    path = path.GetText() # contains the path of the movie file 
    # do some work with the path and do your download 
    wx.CallAfter(a_listbox.SetItem, i, 1, 'OK') # update the listcontrol for each download (wx.CallAfter will force the call to be made in the main thread) 

... 
for i in range(total_items):  
    t = Thread(target = self.Downloader, args = (self.list,i,)) 
    t.start() 

根據您在下面的澄清(您還是應該使用wx.CallAfter)

def Downloader(self): 
    for item_index in range(total_items): 
     path = self.list.GetItem(item_index, 0) # gets the item (first column) from list control 
     path = path.GetText() # contains the path of the movie file 
     # do some work with the path and do your download 
     wx.CallAfter(self.list.SetItem, i, 1, 'OK') # update the listcontrol for 

Thread(target=self.Downloader).start() 
+0

對不起,但這不適用於我的情況。我的程序使用API​​密鑰使用「xmlrpc」請求,並且一次只能從一個用戶帳戶發出一個請求。但是,您提供的代碼一次運行多個請求,從而產生錯誤。看來,我必須找到一種方法來一個接一個地運行線程,而不是一次運行所有線程。 –

+0

...你錯過了點...無論如何看到編輯後 –

+1

謝謝,它的工作。其實,我是線程新手,抱歉沒有明白。 –