线程无效

时间:2014-03-12 14:00:53

标签: python wxpython python-multithreading

我试图让这个小文件复制应用程序工作,显示进度条,但我不明白为什么这不起作用,因为它在更新仪表时锁定了gui。

import shutil
import os
import threading
import wx

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

        self.source = os.path.expanduser("~/Desktop/FolderToCopy")
        self.destination = os.path.expanduser("~/Desktop/BackupFolder/Temp")

        panel = wx.Panel(self, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        hbox4 = wx.BoxSizer(wx.HORIZONTAL)

        self.getSourceSize = self.get_size(self.source)

        self.gauge = wx.Gauge(panel, -1, self.getSourceSize, size=(150, 25))
        self.btn1 = wx.Button(panel, wx.ID_OK)
        self.abortButton = wx.Button(panel, label="Abort")

        self.Bind(wx.EVT_BUTTON, self.OnButtonSelect, self.btn1)
        self.abortButton.Bind(wx.EVT_BUTTON, self.OnAbortButton, self.abortButton)

        hbox1.Add(self.gauge, 1, wx.ALIGN_CENTRE)
        hbox2.Add(self.btn1, 1, wx.RIGHT, 10)
        hbox4.Add(self.abortButton, 1, wx.RIGHT, 20)
        vbox.Add((0, 50), 0)
        vbox.Add(hbox1, 0, wx.ALIGN_CENTRE)
        vbox.Add((0, 30), 0)
        vbox.Add(hbox2, 1, wx.ALIGN_CENTRE)
        vbox.Add(hbox4, 1, wx.ALIGN_CENTRE)
        panel.SetSizer(vbox)
        self.Centre()

    def OnAbortButton(self, e):
        self.shouldAbort = True

    def get_size(self, start_path):
        total_size = 0
        for dirpath, dirnames, filenames in os.walk(start_path):
            for f in filenames:
                fp = os.path.join(dirpath, f)
                total_size += os.path.getsize(fp)
        total_size = total_size / 50
        return total_size

    def OnButtonSelect(self, event):
        thread1 = threading.Thread(target=shutil.copytree, args=(self.source, self.destination))
        thread1.start()
        self.thread1 = threading.Thread(target=self.OnGo(self))
        self.thread1.start()

    def OnCopy(self):
        shutil.copytree(self.source, self.destination)

    def OnGo(self, event):
        self.shouldAbort = False
        getDestinationSize = 0
        get_size = self.get_size
        while getDestinationSize < self.getSourceSize:
            getDestinationSize = get_size(self.destination)
            self.gauge.SetValue(getDestinationSize)
            if self.shouldAbort:
                break

app = wx.App(0)
frame = MyFrame(None, -1, 'gauge.py')
frame.Show(True)
app.MainLoop()

1 个答案:

答案 0 :(得分:4)

    self.thread1 = threading.Thread(target=self.OnGo(self))
    self.thread1.start()

在线程开始之前,您正在此行上执行self.onGo。应通过args传递目标的参数。由于OnGo实际上从未使用其event参数,因此您只需传入无。

    self.thread1 = threading.Thread(target=self.OnGo, args=(None,))
    self.thread1.start()