How to create a pop up message when a button is pressed in Python – Tkinter?
In this article, we will see how to create a button and how to show a popup message when a button is pressed in Python. Tkinter is a standard Python Package for creating GUI applications. Tkinter may be a set of wrappers that implement the Tk widgets as Python classes. Python, when combined with Tkinter, provides a quick and straightforward way to create GUI applications.
Steps to create a Simple GUI in Python using Tkinter:
- Import Tkinter package and all of its modules.
- Create a GUI application root window (root = Tk()) and widgets will be inside the main window.
- Use mainloop() to call the endless loop of the window. If you forget to call this nothing will appear to the user. The window will await any user interaction till we close it.
Syntax : W = Button(root, options)
main: Represents the root window.
options: Its used for widgets. It can be used as key-value pairs separated by commas.
Example 1:
Python3
from tkinter import *
import tkinter.messagebox
root = tkinter.Tk()
root.title( "When you press a button the message will pop up" )
root.geometry( '500x300' )
def onClick():
tkinter.messagebox.showinfo( "Welcome to GFG." , "Hi I'm your message" )
button = Button(root, text = "Click Me" , command = onClick, height = 5 , width = 10 )
button.pack(side = 'bottom' )
root.mainloop()
|
Output:
Output After clicking “Click me”
Example 2:
Python3
from tkinter import *
import tkinter.messagebox
root = tkinter.Tk()
root.title( "When you press a any button the message will pop up" )
root.geometry( '500x300' )
def East():
tkinter.messagebox.showinfo( "Welcome to GFG" , "East Button clicked" )
def West():
tkinter.messagebox.showinfo( "Welcome to GFG" , "West Button clicked" )
def North():
tkinter.messagebox.showinfo( "Welcome to GFG" , "North Button clicked" )
def South():
tkinter.messagebox.showinfo( "Welcome to GFG" , "South Button clicked" )
Button1 = Button(root, text = "West" , command = West, pady = 10 )
Button2 = Button(root, text = "East" , command = East, pady = 10 )
Button3 = Button(root, text = "North" , command = North, pady = 10 )
Button4 = Button(root, text = "South" , command = South, pady = 10 )
Button1.pack(side = LEFT)
Button2.pack(side = RIGHT)
Button3.pack(side = TOP)
Button4.pack(side = BOTTOM)
root.mainloop()
|
Output 2:
Output After clicking “North”
Output After clicking “East”
Last Updated :
26 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...