在感谢另一个成员定义我的单词计数方法之后,我现在正在创建一个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))
答案 0 :(得分: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()