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)

我尝试创建一个新线程,但它没有帮助。谁能帮我

4

1 回答 1

0

在这段代码中有两个错误:

def download(self):
    self.text.SetLabel('Downloading...')
    threading.Thread(None, target=self.getfile.download_file(self.res_html))
  1. 您必须调用 的start()方法Thread才能执行target
  2. target应该是一个callable,但是这样做:

    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)
    

    这样,该函数将在不同的线程中调用。


样式说明:您不必None创建时指定Thread

worker = threading.Thread(target=lambda: self.getfile.download_file(self.res_html))
worker.start()
于 2013-10-02T06:06:14.423 回答