How to handle a Button click event in tkinter?


Sometimes, handling events in a Tkinter application can become a daunting task for us. We have to manage the action and events which need to be executed at the time of running the application. The Button widget is useful for handling such events. We can use Button widget to perform a certain task or event by passing the callback in the command.

While giving the command to the Button widget, we can have an optional lambda or anonymous functions which interpret to ignore any errors in the program. These are just like a general function but they don't have any function bodies in it.


In this example, we will create a button and pass the function to show a popup message on the window.

# Import the required libraries
from tkinter import *
from tkinter import messagebox
from tkinter import ttk

# Create an instance of tkinter frame
win= Tk()

# Set the size of the tkinter window

# Define a function to show the popup message
def show_msg():
   messagebox.showinfo("Message","Hey There! I hope you are doing well.")

# Add an optional Label widget
Label(win, text= "Welcome Folks!", font= ('Aerial 17 bold italic')).pack(pady= 30)

# Create a Button to display the message
ttk.Button(win, text= "Click Here", command=show_msg).pack(pady= 20)


Running the above code will display a window with a Button widget. When we click the button, it will trigger an event to happen.

Now, click the Button to see the event of displaying the popup message on the screen.

Updated on 08-Jun-2021 09:29:37