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

关闭子窗口后如何仅激活直接父窗口而非全部前序窗口?

问题分析与解决方案

问题出在窗口焦点抓取(grab)的传递逻辑上:每次打开新窗口时,grab_set()会将焦点完全转移到新窗口,覆盖父窗口的抓取状态。当关闭最内层窗口(window_3)时,原有的抓取状态没有被恢复,导致所有上层窗口(window_2和window_1)同时获得焦点。

修复方案

在子窗口关闭后,手动将焦点抓取状态恢复到其父窗口,确保只有直接父窗口被激活,更上层窗口保持锁定。

修正后的代码

from tkinter import *

class Second_Child_Win():
    def __init__(self):
        self.root = Toplevel()
        self.root.geometry('200x200')
        self.root.grab_set()

    def run(self, first_child_root):
        Button(self.root, text='Quit', command=self.root.destroy).pack()
        first_child_root.wait_window(self.root)
        # 子窗口关闭后,恢复父窗口的焦点抓取
        first_child_root.grab_set()

class First_Child_Win():
    def __init__(self):
        self.root = Toplevel()
        self.root.geometry('200x200')
        self.root.grab_set()

    def run(self, main_root):
        Button(self.root, text='click', command=self.open_new_win).pack()
        main_root.wait_window(self.root)

    def open_new_win(self):
        A = Second_Child_Win()
        A.run(self.root)

class Main():
    def __init__(self):
        self.root = Tk()
        self.root.geometry('200x200')

    def run(self):
        Button(self.root, text='click', command=self.open_new_win).pack()
        self.root.mainloop()

    def open_new_win(self):
        A = First_Child_Win()
        A.run(self.root)

A = Main()
A.run()

关键修改说明

在Second_Child_Win的run方法中,添加了first_child_root.grab_set():

  • 当window_3关闭后,立即将焦点抓取状态恢复到window_2,确保只有window_2被激活,window_1保持锁定状态。
  • 遵循同样的逻辑,如果后续有更多层级的窗口,只需在每一层子窗口关闭后恢复父窗口的grab_set()即可。

内容的提问来源于stack exchange,提问作者chikibamboni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:45:08