Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a Button click event

I'm just learning Python and I have the base concept down, and already a few command line programs. I'm now learning how to create GUIs with Tkinter.

I created a simple GUI to accept some user information from a Entry widget, and then, when the user clicks submit, it should pop up a dialog.

The dialog should ask for the first name and last name.

The problem is that I don't know how to handle the event when the user clicks submit.

Here's my code:

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 = Entry(master)
        self.fnameEntry.grid()

        self.lnameLabel = Label(master, text="Last Name")
        self.lnameLabel.grid()

        self.lnameEntry = Entry(master)
        self.lnameEntry.grid()

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


    def buttonClick(self, event):
        """ handle button click event and output text from entry area"""
        pass


if __name__ == "__main__":
    guiFrame = GUI()
    guiFrame.mainloop()
like image 467
Orboss Avatar asked Jul 29 '11 14:07

Orboss


People also ask

What is a button click event?

The Click event is raised when the Button control is clicked. This event is commonly used when no command name is associated with the Button control (for instance, with a Submit button). For more information about handling events, see Handling and Raising Events.

When you click on the button which event handler gets called?

Event Handlers − When an event happens and we have registered an event listener for the event, the event listener calls the Event Handlers, which is the method that actually handles the event.

Which method is used to set a click event on a button?

jQuery click() Method The click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.


1 Answers

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.

like image 92
joaquin Avatar answered Oct 05 '22 07:10

joaquin