1437
1437

Reputation: 13

How to make buttons call functions

After defining my word count method thanks to another member, I am now creating a GUI to go along with it. I have created three buttons, one for browsing for a file, one for counting the words and lines in a file, and one for exiting.

My question is, how do I make these buttons do things? I am trying to make the "Browse for a file" run the filename = fileopenbox() line, and the "Count" button run the word_count() method.

Here is what the code looks like:

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))

Upvotes: 0

Views: 2451

Answers (1)

A. Rodas
A. Rodas

Reputation: 20679

You have to pass the reference to the function you want to execute as the command option. Since you are divinding the task in two steps (one button to ask for the file name, and another one to count the lines and the words), I'd suggest you to create a class to wrap everything.

Besides, I suggest you to remove the dependency of easygui - since it is a project that is not longer maintained - and replace it with filedialog.askopenfilename, which is part of the standard library:

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()

Upvotes: 2

Related Questions