Python 如何使按钮调用函数

Python 如何使按钮调用函数,python,user-interface,python-3.x,Python,User Interface,Python 3.x,多亏了另一个成员定义了我的单词计数方法,现在我正在创建一个GUI来配合它。我创建了三个按钮,一个用于浏览文件,一个用于计算文件中的单词和行数,还有一个用于退出 我的问题是,如何让这些按钮发挥作用?我试图让“浏览文件”运行filename=fileopenbox()行,“计数”按钮运行word\u Count()方法 下面是代码的样子: from tkinter import * from easygui import fileopenbox root = Tk() root.title("Wo

多亏了另一个成员定义了我的单词计数方法,现在我正在创建一个GUI来配合它。我创建了三个按钮,一个用于浏览文件,一个用于计算文件中的单词和行数,还有一个用于退出

我的问题是,如何让这些按钮发挥作用?我试图让“浏览文件”运行
filename=fileopenbox()
行,“计数”按钮运行
word\u Count()
方法

下面是代码的样子:

from tkinter import *
from easygui import fileopenbox

root = Tk()
root.title("Word Counter")
root.geometry("500x500")

app = Frame(root)
app.grid()
button1 = Button(app, text = "Browse for a file")
button1.grid()

button2 = Button(app)
button2.grid()
button2.configure(text ="Count the file")

button3 = Button(app)
button3.grid()
button3["text"] = "Exit"

root.mainloop()

def word_count(filename):
    filename = fileopenbox()
    if not filename.endswith(('.txt', '.py', '.java')):
        print('Are you trying to annoy me? How about giving me a TEXT or SOURCE CODE file, genius?')
        return

    with open(filename) as f:
        n_lines = 0
        n_words = 0
        for line in f:
            n_lines += 1
            n_words += len(line.split())
    print('Your file has {} lines, and {} words'.format(n_lines, n_words))

必须通过
命令
选项传递对要执行的函数的引用。由于您要分两步预测任务(一个按钮用于询问文件名,另一个按钮用于计算行数和单词数),因此我建议您创建一个类来包装所有内容

此外,我建议您删除对
easygui
的依赖关系-因为它是一个不再维护的项目-并将其替换为
filedialog.askopenfilename
,它是标准库的一部分:

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo


class App(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.filename = None
        button1 = Button(self, text="Browse for a file", command=self.askfilename)
        button2 = Button(self, text ="Count the file", command=self.word_count)
        button3 = Button(self, text="Exit", command=master.destroy)
        button1.grid()
        button2.grid()
        button3.grid()
        self.grid()
    def askfilename(self):
        filename = askopenfilename()
        if not filename.endswith(('.txt', '.py', '.java')):
            showwarning('Are you trying to annoy me?', 'How about giving me a TEXT or SOURCE CODE file, genius?')
        else:
            self.filename = filename
    def word_count(self):
        if self.filename:
            with open(self.filename) as f:
                n_lines = 0
                n_words = 0
                for line in f:
                    n_lines += 1
                    n_words += len(line.split())
            showinfo('Result', 'Your file has {} lines, and {} words'.format(n_lines, n_words))
        else:
            showwarning('No file selected', 'Select a file first')


root = Tk()
root.title("Word Counter")
root.geometry("500x500")
app = App(root)
root.mainloop()

将回调作为命令关键字参数传递:
Button(…,command=callback)
我有点困惑,你能给我一个没有“…”的例子吗?我将其解释为“Button(fileopenbox(),command=callback)”,但这只是使fileopenbox()方法运行脚本时立即运行是否有任何方法使控制台的输出显示在Tkinter框架上?@DavonG是的,最简单的方法是使用对话框。我已经更新了答案。嗯,信息似乎出现在标题栏而不是网格中。呵呵@DavonG没错,我没有测试代码。
showinfo
的第一个参数是标题,第二个参数是文本,因此它应该是
showinfo('Result','Your file has…')
。我在答案中也改变了它。添加了一些东西,在你的解决方案之后,到目前为止,每件事情都进展顺利。但最后两个问题(我保证!!!)1。是否有办法更改第2帧左上角的Tkinter图标。当我在浏览文件之前单击“清点文件”时。我想弹出一个错误,说“先选择一个文件”。我该怎么做?