Python Tkinter message box example
Python Tkinter Events and Event Handling: Exercise-1 with Solution
Write a Python program that displays a button using Tkinter. When the button is clicked, display a message box with the message.
Sample Solution:
Python Code:
import tkinter as tk
from tkinter import messagebox
# Function to display the message box
def show_message_box():
messagebox.showinfo("Message", "Button Clicked!")
# Create the main window
root = tk.Tk()
root.title("Message Box Example")
# Create a button widget
button = tk.Button(root, text="Click here to display a message", command=show_message_box)
button.pack(padx=20, pady=20)
# Start the Tkinter main loop
root.mainloop()
Explanation:
In the exercise above -
- Import the necessary modules, including tkinter and messagebox.
- Define a function "show_message_box()" function that displays the message box using messagebox.showinfo() when called.
- Create the main Tkinter window 'root' and set its title.
- Create a button widget labeled "Click here to display a message" and associate it with the "show_message_box()" function using the command parameter.
- Finally, start the Tkinter main loop with “root.mainloop()”, which keeps the GUI application running.
Output:
Flowchart:

Python Code Editor:
Previous: Python Tkinter Events and Event Handling Home.
Next: Python Tkinter label and button example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Summing a sequence of numbers (calculating the sum of zero to ten with skips):
>>> l = range(0,10,2) >>> sum(l) 20
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook