python - 如何响应 tkinter 事件?

标签 python button tkinter

我正在 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/

相关文章:

python - 如何在 python 中发送原始以太网帧?

Python - 将字段和标签添加到嵌套的 json 文件

Python matplotlib - 设置 x 轴刻度

ios - 控制两个不同的collectionview

javascript - 为什么在keydown回调中返回false并不会停止按钮点击事件?

css - html表单中一些单选按钮的问题

python-3.x - Tkinter 专注于弹出窗口

python - Flask:异步响应客户端

python - Tkinter 按钮不运行命令

python - Tkinter GUI、I/O 和线程 : When to use queues, 何时发生事件?