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()
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With