线程无法正常工作
我正在尝试让这个小文件复制应用程序正常工作,它会显示一个进度条。但是我不明白为什么它会这样,因为在更新进度条的时候,界面就会卡住。
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 个回答
5
self.thread1 = threading.Thread(target=self.OnGo(self))
self.thread1.start()
self.thread1 = threading.Thread(target=self.OnGo, args=(None,))
self.thread1.start()
在这一行,你正在执行 self.onGo
,但这时候线程还没有开始。要给目标函数传递参数,应该通过 args
来传递。因为 OnGo
实际上并没有用到它的 event
参数,所以你可以直接传入 None。