CodeGym /Courses /Python SELF EN /Working with Dialogs and Pop-up Windows

Working with Dialogs and Pop-up Windows

Python SELF EN
Level 50 , Lesson 1
Available

1. Standard Dialog Windows

Tkinter has a built-in module called messagebox that lets you display dialog windows like info messages, warnings, errors, and confirmation prompts. These dialogs are super handy for interacting with users and showing notifications.

Importing the messagebox module


from tkinter import messagebox

Main types of dialogs with messagebox

  1. Information Window

    Info windows deliver important details to the user. You use the messagebox.showinfo() function for this.

    
    def show_info():
        messagebox.showinfo("Information", "This is an info message")
                
  2. Warning

    A warning window gives a heads-up about a potential issue or suggests paying attention to something specific. The messagebox.showwarning() function creates a warning window.

    
    def show_warning():
        messagebox.showwarning("Warning", "This is a warning message")
                
  3. Error Window

    An error window is shown when something goes wrong. The messagebox.showerror() function is ideal for telling users about errors.

    
    def show_error():
        messagebox.showerror("Error", "An error occurred!")
                
  4. Action Confirmation Prompt

    Confirmation prompts let users either confirm or cancel an action. The messagebox.askyesno() function returns True or False based on the user's choice.

    
    def confirm_exit():
        response = messagebox.askyesno("Exit", "Are you sure you want to exit?")
        if response:
            root.quit()
                

2. Selecting Files and Folders

Tkinter provides the filedialog module, which allows users to pick files and folders. This is super useful in apps that work with files where users need to load or save something.

Importing the filedialog module


from tkinter import filedialog

Main functions of filedialog

  1. Opening a File: The askopenfilename() function lets users pick a file to open.
    
    def open_file():
        file_path = filedialog.askopenfilename(
            title="Open File",
            filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
        if file_path:
            print("Selected file:", file_path)
                
  2. Saving a File: The asksaveasfilename() function lets users pick a path and name for saving their file.
    
    def save_file():
        file_path = filedialog.asksaveasfilename(
            title="Save File",
            defaultextension=".txt",
            filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
        if file_path:
            print("File saved as:", file_path)
                
  3. Selecting a Folder: The askdirectory() function lets users select a folder.
    
    def select_directory():
        directory_path = filedialog.askdirectory(title="Select Folder")
        if directory_path:
            print("Selected folder:", directory_path)
                

3. Custom Pop-up Windows

Besides standard dialog windows, Tkinter provides the Toplevel widget for creating customizable pop-up windows. Use these for making versatile pop-ups with input fields, buttons, and other UI elements.

Creating a Pop-up Window with Toplevel


import tkinter as tk

# Function to open the pop-up window
def open_popup():
    popup = tk.Toplevel(root)
    popup.title("Pop-up Window")
    popup.geometry("300x200")

    label = tk.Label(popup, text="Enter your name:")
    label.pack(pady=10)

    entry = tk.Entry(popup)
    entry.pack(pady=5)

    # Button to close the window
    close_button = tk.Button(popup, text="Close", command=popup.destroy)
    close_button.pack(pady=10)

# Main window
root = tk.Tk()
root.title("Main Window")
root.geometry("400x300")

# Button to call the pop-up window
open_button = tk.Button(root, text="Open Pop-up Window", command=open_popup)
open_button.pack(pady=50)

root.mainloop()
    

Code Explanation

  • tk.Toplevel(root) creates a new window that appears on top of the main root window.
  • Window Elements: You can add labels, input fields, and buttons inside the pop-up window.
  • "Close" Button: The popup.destroy function closes the pop-up window.

4. Complete App with Dialogs and Pop-ups

Now, let's combine all these elements into a single app, featuring standard dialogs, file selection, and a custom pop-up window.


import tkinter as tk
from tkinter import messagebox, filedialog

# Functions for standard dialogs
def show_info():
    messagebox.showinfo("Information", "This is an info message")

def show_warning():
    messagebox.showwarning("Warning", "This is a warning message")

def show_error():
    messagebox.showerror("Error", "An error occurred!")

def confirm_exit():
    response = messagebox.askyesno("Exit", "Are you sure you want to exit?")
    if response:
        root.quit()

def open_file():
    file_path = filedialog.askopenfilename(title="Open File", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
    if file_path:
        messagebox.showinfo("Selected File", file_path)

def save_file():
    file_path = filedialog.asksaveasfilename(title="Save File", defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")])
    if file_path:
        messagebox.showinfo("File Saved As", file_path)

def select_directory():
    directory_path = filedialog.askdirectory(title="Select Folder")
    if directory_path:
        messagebox.showinfo("Selected Folder", directory_path)

# Function for custom pop-up window
def open_popup():
    popup = tk.Toplevel(root)
    popup.title("Pop-up Window")
    popup.geometry("300x200")

    tk.Label(popup, text="Enter your name:").pack(pady=10)
    name_entry = tk.Entry(popup)
    name_entry.pack(pady=5)

    tk.Button(popup, text="Close", command=popup.destroy).pack(pady=10)

# Main window
root = tk.Tk()
root.title("App with Dialogs and Pop-ups")
root.geometry("400x400")

# Buttons to trigger various dialogs and pop-ups
tk.Button(root, text="Information", command=show_info).pack(pady=5)
tk.Button(root, text="Warning", command=show_warning).pack(pady=5)
tk.Button(root, text="Error", command=show_error).pack(pady=5)
tk.Button(root, text="Exit Confirmation", command=confirm_exit).pack(pady=5)
tk.Button(root, text="Open File", command=open_file).pack(pady=5)
tk.Button(root, text="Save File", command=save_file).pack(pady=5)
tk.Button(root, text="Select Folder", command=select_directory).pack(pady=5)
tk.Button(root, text="Open Pop-up Window", command=open_popup).pack(pady=20)

root.mainloop()
    
1
Task
Python SELF EN, level 50, lesson 1
Locked
Creating a Simple Information Window
Creating a Simple Information Window
2
Task
Python SELF EN, level 50, lesson 1
Locked
Exit Confirmation Request
Exit Confirmation Request
3
Task
Python SELF EN, level 50, lesson 1
Locked
Opening and saving a file
Opening and saving a file
4
Task
Python SELF EN, level 50, lesson 1
Locked
Creating a Custom Popup Window
Creating a Custom Popup Window
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION