You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

  1. 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.
  2. Focus Redirection:

    • The redirect_to_toplevel function 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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 04:17:10