2013-10-02 82 views
0

我寫音樂下載,下載需要一段時間和GUI凍結而發生這種情況,所以我怎樣才能讓這個圖形用戶界面保持在下載會線程一個GUI

下面是相關的代碼運行:

class GUI(wx.Frame): 
    def __init__(self, parent, id, title): 

     self.retreive_range = 10 
     self.convert_range = 10 
     self.download_range = 100 

     self.timer1 = wx.Timer(self, 1) 
     self.timer2 = wx.Timer(self, 1) 
     self.timer3 = wx.Timer(self, 1) 

     self.count = 0 
     self.count2 = 0 
     self.count3 = 0 

     self.getfile = Get_file() 

     self.Bind(wx.EVT_TIMER, self.OnTimer1, self.timer1) 

     #All the GUI code! 


    def retrieve(self, e): 
     self.timer1.Start(100) 
     self.text.SetLabel('Retrieving URL...') 
     query = self.tc.GetValue() 
     self.vidurl = self.getfile.get_url(query) 



    def convert(self): 
     self.timer2.Start(200) 
     self.text.SetLabel('Converting...') 
     self.res_html = self.getfile.get_file('http://www.youtube.com/%s'%self.vidurl) 
     print self.res_html 

    def download(self): 
     self.text.SetLabel('Downloading...') 
     threading.Thread(None, target=self.getfile.download_file(self.res_html)) 



    def OnTimer1(self, e): 

     self.count = self.count + 1 
     self.gauge.SetValue(self.count) 

     if self.count == self.retreive_range: 

      self.timer1.Stop() 
      self.text.SetLabel('Url Retreived!') 
      self.Bind(wx.EVT_TIMER, self.OnTimer2, self.timer2) 
      self.convert() 

    def OnTimer2(self, e): 

     self.count2 = self.count2 + 1 
     self.gauge.SetValue(self.count2) 

     print self.count2 

     if self.count2 == self.convert_range: 

      self.timer2.Stop() 
      self.text.SetLabel('Converted!') 
      self.Bind(wx.EVT_TIMER, self.OnTimer3, self.timer3) 
      self.download() 

    def OnTimer3(self, e): 

     self.count3 = self.count3 + 0.5 
     self.gauge.SetValue(self.count3) 

     if self.count3 == self.download_range: 

      self.timer3.Stop() 
      self.text.SetLabel('Downloaded!') 
      self.gauge.SetValue(0) 

我嘗試創建一個新的線程,但它沒有幫助。誰能幫助我

回答

0

在這段代碼中有兩個誤區:

def download(self): 
    self.text.SetLabel('Downloading...') 
    threading.Thread(None, target=self.getfile.download_file(self.res_html)) 
  1. 必須調用Threadstart()方法,以便其執行target
  2. target應一個可調用,但是這樣做:

    target=self.getfile.download_file(self.res_html) 
    

    在創建Thread之前,您已經調用函數,然後將返回值分配給target。這是你看到GUI凍結。你必須使用一個lambda

    target=lambda: self.getfile.download_file(self.res_html) 
    

    或者functools.partial

    target=partial(self.getfile.download_file, self.res_html) 
    

    這樣的功能會在不同的線程調用。


樣式注意:您有創建Thread時指定None

worker = threading.Thread(target=lambda: self.getfile.download_file(self.res_html)) 
worker.start() 
+0

好吧,我看看!它的工作非常感謝! – Serial