练习:Python版小型下载工具
时间:2009-07-23 来源:应该早习惯
# _*_ coding: utf-8 _*_
import urllib
from Tkinter import Scale, Button, StringVar, Label,\
Text, Frame, Tk, LEFT, Entry, HORIZONTAL
#from Tkinter import *
import time
import tkMessageBox
import re
top = Tk()
top.title('Python版小型下载工具')
topLabel = Label(top, text='Python Download v1.1')
topLabel.pack()
urlString = StringVar(top)
pathString = StringVar(top)
urlFrame = Frame(top)
urlLabel = Label(urlFrame, text='URL地址')
urlLabel.pack(side=LEFT)
urlEntry = Entry(urlFrame, width=50, textvariable=urlString)
urlEntry.pack(side=LEFT)
urlFrame.pack()
pathFrame = Frame(top)
pathLabel = Label(pathFrame, text='保存地址')
pathLabel.pack(side=LEFT)
pathEntry = Entry(pathFrame, width=50, textvariable=pathString)
pathEntry.pack(side=LEFT)
pathFrame.pack()
proFrame = Frame(top)
proLabel = Label(proFrame, text='进度%')
proLabel.pack(side=LEFT)
proSacle = Scale(proFrame, length=300, from_=0, to=100.0,
resolution = 0.01,
orient=HORIZONTAL)
proSacle.pack(side=LEFT)
proFrame.pack()
buttonFrame = Frame(top)
downButton = Button(buttonFrame, text='下载',
# command=downFunc,
activeforeground='white',
activebackground='blue')
downButton.pack(side=LEFT)
quit = Button(buttonFrame, text='退出',
command=top.quit,
activeforeground='white',
activebackground='red')
quit.pack(side=LEFT)
buttonFrame.pack()
def downFunc():
url = urlString.get()
if url == '':
tkMessageBox.showwarning('Error', 'URL地址为空!')
elif re.match('http://|ftp://',url) is None:
tkMessageBox.showwarning('Error', '错误类型的URL地址!!')
path = pathString.get()
if path == '':
tkMessageBox.showwarning('Error', '保存地址错误!')
try:
(filename, mine_hdrs) = urllib.urlretrieve(url, path, reportHook)
except IOError, e:
print e
pass
else:
tkMessageBox.showinfo('Info','download %s finished'%filename)
top.update()
downButton.configure(command=downFunc)
def reportHook(blocknum, bs, size):
transBytes = blocknum*bs
a = float(transBytes)/size*100
proSacle.set(a)
top.update()
top.mainloop()
下一步的工作是集中于downFunc函数的处理,以及用OOP处理整个程序。
请教各位高手一个问题,怎样在一个类里面处理Hook(钩子)函数?上面程序def reportHook(blocknum, bs, size)是一个钩子函数,Python规定其参数为3个。如果将其放到类里面,则应要4个函数,这样一来就无法调用了。不知大家是怎么处理这个问题的。