Python: How to create GUI pop-up windows with Tkinter

When creating a program in Python, a useful thing to be able to do is to have a pop-up window appear on the screen with a special message. This can be used to give instant feedback to the user, alert the user to an error, or inform the user that the program completed successfully.

In Python this can be done using the Tkinter module with the following code, which I have placed into an easy to use function:

from Tkinter import *

def alert_popup(title, message, path):
    """Generate a pop-up window for special messages."""
    root = Tk()
    root.title(title)

    w = 400     # popup window width
    h = 200     # popup window height

    sw = root.winfo_screenwidth()
    sh = root.winfo_screenheight()

    x = (sw - w)/2
    y = (sh - h)/2
    root.geometry('%dx%d+%d+%d' % (w, h, x, y))

    m = message
    m += '\n'
    m += path
    w = Label(root, text=m, width=120, height=10)
    w.pack()
    b = Button(root, text="OK", command=root.destroy, width=10)
    b.pack()
    mainloop()


# Examples
alert_popup("Title goes here..", "Hello World!", "A path or second message can go here..")

alert_popup("Success!", "Processing completed. Your report was saved here:", "C:/path/to/my_reports/report1.xlsx")

To use this function, you must import the Tkinter module. The width and height of the pop-up window can be defined inside the function. This function takes in the title you want for the alert, a main message, and a second message which can optionally be left empty.

Here are what the two examples in the code look like:

 

Leave a Reply