线程不起作用 [英] Threading not working
本文介绍了线程不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让这个显示进度条的小文件复制应用程序正常工作,但我不明白为什么这不起作用,因为它在更新仪表的同时锁定了 gui.
I am trying to get this little file copy application working which shows a progress bar, but I am not understanding why this won't work, as it locks up the gui whilst updating the gauge.
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()
推荐答案
self.thread1 = threading.Thread(target=self.OnGo(self))
self.thread1.start()
您正在这一行上执行 self.onGo
,甚至在线程开始之前.目标的参数应该通过 args
传入.由于 OnGo
从不实际使用它的 event
参数,您可以只传入 None.
You're executing self.onGo
on this line, before the thread even starts. Arguments to the target should be passed in via args
. Since OnGo
never actually uses its event
parameter, you can just pass in None.
self.thread1 = threading.Thread(target=self.OnGo, args=(None,))
self.thread1.start()
这篇关于线程不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文