如何将Toplevel设为主窗口并限制主窗口切换行为
Solution for Toplevel as Primary Window with Focus Redirection
Here's how to implement your two requirements using Tkinter:
Key Approach
- Set Toplevel as the primary window: Configure the Toplevel to control application shutdown and prioritize it visually.
- Redirect focus from original main window: Bind a focus event to the original window that forces the Toplevel back into focus whenever the user tries to activate the main window.
Complete Code Example
import tkinter as tk def redirect_to_toplevel(event): # Bring Toplevel to front and claim focus top.lift() top.focus_set() # Ensure main window doesn't retain focus event.widget.focus_force() top.focus_set() # Initialize original main window root = tk.Tk() root.title("Original Main Window") root.geometry("300x200") # Create and configure the Toplevel window top = tk.Toplevel(root) top.title("Primary Toplevel Window") top.geometry("300x200") # Make Toplevel control app exit (like a main window) top.protocol("WM_DELETE_WINDOW", root.quit) # Bind focus event to redirect from main window to Toplevel root.bind("<FocusIn>", redirect_to_toplevel) # Optional: Hide original main window entirely (uncomment if needed) # root.withdraw() # Start the application loop root.mainloop()
Explanation
Toplevel as Primary Window:
top.protocol("WM_DELETE_WINDOW", root.quit)ensures closing the Toplevel exits the entire application, mimicking the behavior of the original main window.- The Toplevel is initialized as a child of the main window, maintaining proper application hierarchy.
Focus Redirection:
- The
redirect_to_toplevelfunction triggers whenever the original main window receives focus. It lifts the Toplevel to the top of the window stack and sets focus to it, preventing the main window from becoming active. - If you don’t want the original main window visible at all, uncomment
root.withdraw()—this hides it from the screen and taskbar while keeping it active in the background.
- The
Note: Focus handling may vary slightly across operating systems, but this implementation works consistently on Windows, macOS, and Linux for most use cases.
内容的提问来源于stack exchange,提问作者Steklyashka
相关产品推荐
相关产品推荐

