【问题标题】:How to respond to tkinter events?如何响应 tkinter 事件?
【发布时间】: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()

现在我不知道如何组装我的代码,以便在按下按钮时运行。

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    主要问题是tkFileDialog.askopenfile() 返回一个打开的file 而不是文件名。以下似乎或多或少对我有用:

    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 模块,用于执行此类操作。

    【讨论】:

    • 在 3 分钟内击败... +1 好答案,也比我的要简单得多。
    【解决方案2】:

    尝试一些类似这样的布局:

    class my_app():
        def __init__():
            self.hi_there = Tkinter.Button(frame, text="Hello", command=self.say_hi)
            self.hi_there.pack(side=Tkinter.LEFT)
    
        def say_hi():
            # do stuff
    

    您可能还想阅读:

    This tutorial on Tkinter,

    And this one.

    编辑: OP 想要一个带有他的代码的示例(我认为)所以这里是:

    from Tkinter import *               
    import tkFileDialog,Tkconstants,collections
    
    class my_app:
        def __init__(self, master):
            frame = Tkinter.Frame(master)
            frame.pack()
    
            self.button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
            self.button = Button(frame, text = 'Open .txt file', fg = 'black', command= self.openFile).pack(**button_opt)
    
            self.calc_button = Button(frame, text = 'Calculate', fg = 'black', command= self.calculate).pack()
    
            self.fileName = ''
    
        def openFile():
            fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")])
    
        def calculate():
            ############################################### *See note
            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 = Tk()
    
    app = App(root)
    
    root.title("TEST")
    root.geometry("800x600")
    
    root.mainloop()
    

    *注意:在您的代码中,我没有看到集合来自哪里,所以我不太确定如何处理该块。在此示例中,我已将其设置为在

    【讨论】:

    • 感谢您的帮助,但我仍然无法正常工作。你能复制你的例子的代码吗?
    【解决方案3】:

    在您的openFile() 函数中,在您向用户询问文件名之后,输入您的代码!

    【讨论】:

    • 好吧,这不起作用,我试过了,但是当我运行它时,首先打开窗口对话框,打开 text.file。我想要按钮,然后单击它并打开 .txt 文件,然后执行“代码”中的操作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2021-05-29
    • 2018-05-19
    • 1970-01-01
    相关资源
    最近更新 更多