How to handle a Button click event How to handle a Button click event tkinter tkinter

How to handle a Button click event


You already had your event function. Just correct your code to:

   """Create Submit Button"""    self.submitButton = Button(master, command=self.buttonClick, text="Submit")    self.submitButton.grid()def buttonClick(self):    """ handle button click event and output text from entry area"""    print('hello')    # do here whatever you want

This is the same as in @Freak's answer except for the buttonClick() method is now outside the class __init__ method. The advantage is that in this way you can call the action programmatically. This is the conventional way in OOP-coded GUI's.


You should specify a handler, or a function, that is called when you click the Button. You can do this my assigning the name (not calling the function) of the function to the property command of your Button.

For example:

self.submitButton = Button(self.buttonClick, text="Submit", command=buttonClick)

Note the absence of () when assigning buttonClick as the command property of self.submitButton.

Note that you don't need the second parameter called event in your handler/function buttonClick().


I found a pretty good reference called Thinking in Tkinter, and I butchered it up a bit. I tried to fit it for what you wanted.

from tkinter import *class GUI(Frame):    def __init__(self,master=None):        Frame.__init__(self, master)        self.grid()        self.fnameLabel = Label(master, text="First Name")        self.fnameLabel.grid()        self.fnameEntry = StringVar()        self.fnameEntry = Entry(textvariable=self.fnameEntry)        self.fnameEntry.grid()        self.lnameLabel = Label(master, text="Last Name")        self.lnameLabel.grid()        self.lnameEntry = StringVar()        self.lnameEntry = Entry(textvariable=self.lnameEntry)        self.lnameEntry.grid()        def buttonClick():            print("You pressed Submit!")            print(self.fnameEntry.get() + " " + self.lnameEntry.get() +",                  you clicked the button!")        self.submitButton = Button(master, text="Submit", command=buttonClick)        self.submitButton.grid()if __name__ == "__main__":    guiFrame = GUI()        guiFrame.mainloop()