0

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

我的问题是,我如何让这些按钮做事?我试图让“浏览文件”运行该filename = fileopenbox()行,而“计数”按钮运行该word_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))
4

1 回答 1

2

您必须将引用传递给要作为command选项执行的函数。由于您将任务分为两步(一个按钮询问文件名,另一个按钮计算行数和单词),我建议您创建一个类来包装所有内容。

此外,我建议您删除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()
于 2013-06-15T20:06:35.583 回答