感谢另一位成员定义了我的字数统计方法后,我现在正在创建一个 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))