<p>有多种方法可以组织代码。有一种方法:</p>
<pre><code>import hashlib
import Tkinter as tk
from tkFileDialog import askopenfilename
class Application(object):
def __init__(self):
self.root = root = tk.Tk()
menubar = tk.Menu(root)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Hash", command=self.hashmd5)
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
#Add a Label to hold the current filename
self.filename = tk.StringVar()
self.filename.set("No File Selected")
lbl = tk.Label(root, textvariable=self.filename, anchor="w")
lbl.pack()
#Add a Label to hold the most recent MD5 digest
self.digest = tk.StringVar()
lbl = tk.Label(root, textvariable=self.digest, anchor="w")
lbl.pack()
root.mainloop()
def hashmd5(self):
BLOCKSIZE = 65536
hasher = hashlib.md5()
filename = askopenfilename(parent=self.root)
self.filename.set(filename)
print(filename)
with open(filename, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
digest = hasher.hexdigest()
self.digest.set(digest)
print(digest)
Application()
</code></pre>
<p>如果您在python3上运行这个命令,您需要更改Tkinter import语句。你知道吗</p>