【发布时间】:2010-12-12 22:29:47
【问题描述】:
我正在 python 中使用 GUI 做一些工作。我正在使用 Tkinter 库。
我需要一个按钮,它将打开一个 .txt 文件并进行以下处理:
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
我开始:
from Tkinter import *
import tkFileDialog,Tkconstants,collections
root = Tk()
root.title("TEST")
root.geometry("800x600")
button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
fileName = ''
def openFile():
fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")])
Button(root, text = 'Open .txt file', fg = 'black', command= openFile).pack(**button_opt)
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
root.mainloop()
现在我不知道如何组装我的代码,以便在按下按钮时运行。
【问题讨论】: