如何处理按钮单击事件

如何处理按钮单击事件

本文介绍了如何处理按钮单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Python,我已经掌握了基本概念,并且已经有了一些命令行程序。我现在正在学习如何使用Tkinter创建GUI。

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.

我创建了一个简单的GUI来接受 Entry 小部件中的一些用户信息,然后在用户单击时

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.

这是我的代码:

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


推荐答案

您已经具有事件功能。只需将代码更正为:

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

除了 buttonClick()方法现在在类 __ init __ 方法。这样做的好处是,您可以以编程方式调用该动作。这是OOP编码的GUI中的常规方式。

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.

这篇关于如何处理按钮单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 16:43