Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

python - 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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...