別のメンバーのおかげで単語カウント方法を定義した後、それに合わせて GUI を作成しています。ファイルを参照するためのボタン、ファイル内の単語と行をカウントするためのボタン、および終了するためのボタンの 3 つのボタンを作成しました。
私の質問は、これらのボタンにどのように機能させるのですか? 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))