我正在 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()
现在我不知道如何汇编我的代码,以便它在按下按钮时运行。
最佳答案
主要问题是tkFileDialog.askopenfile()
返回一个打开的文件
而不是文件名。以下内容似乎或多或少对我有用:
from Tkinter import *
import tkFileDialog, Tkconstants,collections
root = Tk()
root.title("TEST")
root.geometry("800x600")
def openFile():
f_in = tkFileDialog.askopenfile(
parent=root,
title="Open .txt file",
filetypes=[("txt file",".txt"),("All files",".*")])
frequencies = collections.defaultdict(int)
for line in f_in:
for char in line:
frequencies[char] += 1
f_in.close()
total = float(sum(frequencies.values()))
print 'total:', total
button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
fileName = ''
Button(root, text = 'Open .txt file',
fg = 'black',
command= openFile).pack(**button_opt)
root.mainloop()
为了快速创建简单的 GUI 程序,我强烈推荐 EasyGUI ,一个相当强大但简单的基于 Tk
的 Python 模块,用于执行此类操作。
关于python - 如何响应 tkinter 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4424469/