Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

create a nice modern popup window with white backround and rounded corners. Use only…

  1. User

    create a nice modern popup window with white backround and rounded corners. Use only tkinter

  2. Assistant

    Creating a popup window with truly rounded corners in Tkinter is a bit challenging because Tkinter doesn't natively support non-rectangular window shapes. However, you can simulate rounded corners by using a combination of a Canvas widget to draw a rounded rectangle and removing the window decorations to give the appearance of a modern, rounded popup.

    Below is an example of how you can achieve this:

    1. Remove Window Decorations: Use the overrideredirect method to remove the default window borders and title bar.
    2. Create a Rounded Rectangle: Use the Canvas widget to draw a rounded rectangle that serves as the background of your popup.
    3. Handle Window Dragging: Since we've removed the window decorations, we'll implement custom dragging functionality to allow users to move the popup.

    Here's the complete Python script using Tkinter:

    import tkinter as tk
    
    class RoundedPopup(tk.Toplevel):
        def __init__(self, parent, width=300, height=200, corner_radius=20, bg="#ffffff"):
            super().__init__(parent)
    
            self.parent = parent
            self.width = width
            self.height = height
            self.corner_radius = corner_radius
            self.bg = bg
    
            # Remove window decorations
            self.overrideredirect(True)
    
            # Set window transparency attributes (platform dependent)
            self.attributes("-topmost", True)
            try:
                # For Windows
                self.attributes("-transparentcolor", "grey")
            except:
                pass
    
            # Center the popup window
            self.geometry(f"{self.width}x{self.height}+{self.center_x()}+{self.center_y()}")
    
            # Create canvas
            self.canvas = tk.Canvas(self, width=self.width, height=self.height, highlightthickness=0, bg='grey')
            self.canvas.pack()
    
            # Draw rounded rectangle
            self.draw_rounded_rect(0, 0, self.width, self.height, self.corner_radius, fill=self.bg, outline=self.bg)
    
            # Example content: a label and a close button
            self.content_frame = tk.Frame(self.canvas, bg=self.bg)
            self.content_frame.place(relx=0.5, rely=0.5, anchor='center')
    
            label = tk.Label(self.content_frame, text="This is a rounded popup!", bg=self.bg, font=("Arial", 14))
            label.pack(pady=20)
    
            close_button = tk.Button(self.content_frame, text="Close", command=self.destroy, bg="#f0f0f0", relief="flat")
            close_button.pack(pady=10)
    
            # Bind events for dragging the window
            self.bind_events()
    
        def center_x(self):
            self.update_idletasks()
            screen_width = self.winfo_screenwidth()
            return (screen_width // 2) - (self.width // 2)
    
        def center_y(self):
            self.update_idletasks()
            screen_height = self.winfo_screenheight()
            return (screen_height // 2) - (self.height // 2)
    
        def draw_rounded_rect(self, x1, y1, x2, y2, r=25, **kwargs):
            points = [
                x1 + r, y1,
                x1 + r, y1,
                x2 - r, y1,
                x2 - r, y1,
                x2, y1,
                x2, y1 + r,
                x2, y1 + r,
                x2, y2 - r,
                x2, y2 - r,
                x2, y2,
                x2 - r, y2,
                x2 - r, y2,
                x1 + r, y2,
                x1 + r, y2,
                x1, y2,
                x1, y2 - r,
                x1, y2 - r,
                x1, y1 + r,
                x1, y1 + r,
                x1, y1,
            ]
            return self.canvas.create_polygon(points, **kwargs, smooth=True)
    
        def bind_events(self):
            self.canvas.bind("<ButtonPress-1>", self.start_move)
            self.canvas.bind("<ButtonRelease-1>", self.stop_move)
            self.canvas.bind("<B1-Motion>", self.do_move)
    
        def start_move(self, event):
            self.x = event.x
            self.y = event.y
    
        def stop_move(self, event):
            self.x = None
            self.y = None
    
        def do_move(self, event):
            deltax = event.x - self.x
            deltay = event.y - self.y
            x = self.winfo_x() + deltax
            y = self.winfo_y() + deltay
            self.geometry(f"+{x}+{y}")
    
    def show_popup():
        popup = RoundedPopup(root)
    
    # Main application window
    root = tk.Tk()
    root.geometry("400x300")
    root.title("Main Window")
    
    open_popup_button = tk.Button(root, text="Open Rounded Popup", command=show_popup, bg="#4CAF50", fg="white", padx=10, pady=5)
    open_popup_button.pack(pady=100)
    
    root.mainloop()
    

    Explanation of the Code:

    1. RoundedPopup Class:

      • Inherits from tk.Toplevel to create a new popup window.
      • Removes the default window decorations using overrideredirect(True).
      • Sets the window to be always on top.
      • Centers the popup on the screen.
      • Creates a Canvas with a gray background that serves as the transparent area.
      • Draws a rounded rectangle on the canvas with the desired background color (self.bg).
      • Places a Frame inside the canvas to hold any content (e.g., labels, buttons).
      • Adds a label and a close button as example content.
      • Implements custom dragging functionality by binding mouse events.
    2. Rounded Rectangle Drawing:

      • The draw_rounded_rect method calculates points to draw a polygon that resembles a rounded rectangle.
      • Uses the smooth=True parameter to curve the edges.
    3. Window Dragging:

      • Since the window decorations are removed, users can't drag the window by default.
      • The bind_events method binds mouse events to enable dragging the window by clicking and dragging anywhere on the canvas.
    4. Main Application:

      • Creates a main window with a button that, when clicked, opens the rounded popup.

    Notes:

    • Transparency and Rounded Corners:

      • True window transparency and non-rectangular shapes are highly platform-dependent and may not work consistently across all operating systems using Tkinter alone.
      • The above approach simulates rounded corners by drawing within the window. The actual window shape remains rectangular, but the visual appearance is that of a rounded popup.
    • Customization:

      • You can customize the width, height, corner_radius, and bg parameters when creating the RoundedPopup to fit your design needs.
      • Add more widgets or styles to the content_frame to enhance the popup's appearance and functionality.
    • Platform Compatibility:

      • The transparency attributes (-transparentcolor) used in the code may work on Windows. For other platforms like macOS or Linux, additional adjustments might be necessary.

    This script provides a foundation for creating modern-looking popup windows in Tkinter with simulated rounded corners. You can expand upon this by adding more sophisticated styles, animations, or integrating with other parts of your Tkinter application.