Skip to main content
 首页 » 编程设计

python之在显示模态窗口时隐藏 Tkinter 根窗口

2024年10月25日7langtianya

我有一个基于 TKinter 的应用程序,它试图管​​理游戏的设置。用户可能安装了该游戏的多个版本,在这种情况下,我需要询问用户他们希望在启动时管理哪个安装。该部分本身就可以很好地工作;构建主窗口后弹出选择对话框,并以模态方式运行。

但是,由于游戏版本之间的差异,如果我可以针对这些情况稍微调整界面,那将会很有用。然而,这意味着我无法真正构建主窗口,直到我知道我正在处理哪个安装,因此在用户做出选择之前它将是空白的。

我想在显示此对话框时隐藏根窗口,但在根窗口上调用 withdraw 只会导致模态对话框也不显示 - Python 最终挂起没有CPU 使用率,而且我无法弄清楚如何在不必求助于非模态窗口(以及明显不同的控制流,我想避免)的情况下解决这个问题。

展示问题和一般代码结构的示例代码(Python 2.7):

from Tkinter import * 
from ttk import * 
 
class TkGui(object): 
    def __init__(self): 
        self.root = root = Tk() 
        self.root.withdraw() 
        selector = FolderSelection(self.root, ('foo', 'bar')) 
        self.root.deiconify() 
        print(selector.result) 
 
class ChildWindow(object): #Base class 
    def __init__(self, parent, title): 
        top = self.top = Toplevel(parent) 
        self.parent = parent 
        top.title(title) 
        f = Frame(top) 
        self.create_controls(f) 
        f.pack(fill=BOTH, expand=Y) 
 
    def create_controls(self, container): 
        pass 
 
    def make_modal(self, on_cancel): 
        self.top.transient(self.parent) 
        self.top.wait_visibility() # Python will hang here... 
        self.top.grab_set() 
        self.top.focus_set() 
        self.top.protocol("WM_DELETE_WINDOW", on_cancel) 
        self.top.wait_window(self.top) # ...or here, if wait_visibility is removed 
 
class FolderSelection(ChildWindow): 
    def __init__(self, parent, folders): 
        self.parent = parent 
        self.listvar = Variable(parent) 
        self.folderlist = None 
        super(FolderSelection, self).__init__(parent, 'Select folder') 
        self.result = '' 
        self.listvar.set(folders) 
        self.make_modal(self.cancel) 
 
    def create_controls(self, container): 
        f = Frame(container) 
        Label( 
            f, text='Please select the folder ' 
            'you would like to use.').grid(column=0, row=0) 
        self.folderlist = Listbox( 
            f, listvariable=self.listvar, activestyle='dotbox') 
        self.folderlist.grid(column=0, row=1, sticky="nsew") 
        Button( 
            f, text='OK', command=self.ok 
            ).grid(column=0, row=2, sticky="s") 
        self.folderlist.bind("<Double-1>", lambda e: self.ok()) 
        f.pack(fill=BOTH, expand=Y) 
 
    def ok(self): 
        if len(self.folderlist.curselection()) != 0: 
            self.result = self.folderlist.get(self.folderlist.curselection()[0]) 
            self.top.protocol('WM_DELETE_WINDOW', None) 
            self.top.destroy() 
 
    def cancel(self): 
        self.top.destroy() 
 
TkGui() 

请您参考如下方法:

在您的情况下,模态窗口与否似乎没有区别。实际上,您只需要使用wait_window() 方法即可。根据docs :

In many situations, it is more practical to handle dialogs in a synchronous fashion; create the dialog, display it, wait for the user to close the dialog, and then resume execution of your application. The wait_window method is exactly what we need; it enters a local event loop, and doesn’t return until the given window is destroyed (either via the destroy method, or explicitly via the window manager).

考虑使用非模态窗口的示例:

from Tkinter import * 
 
root = Tk() 
 
def go(): 
   wdw = Toplevel() 
   wdw.geometry('+400+400') 
   e = Entry(wdw) 
   e.pack() 
   e.focus_set() 
   #wdw.transient(root) 
   #wdw.grab_set() 
   root.wait_window(wdw) 
   print 'done!' 
 
Button(root, text='Go', command=go).pack() 
Button(root, text='Quit', command=root.destroy).pack() 
 
root.mainloop() 

当您单击Go 按钮时,将出现非模态对话框,但代码将停止执​​行并且字符串done! 将仅在您关闭对话框窗口后显示。

如果这是你想要的行为,那么这里是你的修改形式的例子(我修改了 TkGui 中的 __init__ 和 make_modal 方法,还添加了 主循环()):

from Tkinter import * 
from ttk import * 
 
class TkGui(object): 
    def __init__(self): 
        self.root = root = Tk() 
        self.root.withdraw() 
        selector = FolderSelection(self.root, ('foo', 'bar')) 
        self.root.deiconify() 
        print(selector.result) 
 
class ChildWindow(object): #Base class 
    def __init__(self, parent, title): 
        top = self.top = Toplevel(parent) 
        self.parent = parent 
        top.title(title) 
        f = Frame(top) 
        self.create_controls(f) 
        f.pack(fill=BOTH, expand=Y) 
 
    def create_controls(self, container): 
        pass 
 
    def make_modal(self, on_cancel): 
        #self.top.transient(self.parent) 
        #self.top.wait_visibility() # Python will hang here... 
        #self.top.grab_set() 
        self.top.focus_set() 
        self.top.protocol("WM_DELETE_WINDOW", on_cancel) 
        self.top.wait_window(self.top) # ...or here, if wait_visibility is removed 
 
class FolderSelection(ChildWindow): 
    def __init__(self, parent, folders): 
        self.parent = parent 
        self.listvar = Variable(parent) 
        self.folderlist = None 
        super(FolderSelection, self).__init__(parent, 'Select folder') 
        self.result = '' 
        self.listvar.set(folders) 
        self.make_modal(self.cancel) 
 
    def create_controls(self, container): 
        f = Frame(container) 
        Label( 
            f, text='Please select the folder ' 
            'you would like to use.').grid(column=0, row=0) 
        self.folderlist = Listbox( 
            f, listvariable=self.listvar, activestyle='dotbox') 
        self.folderlist.grid(column=0, row=1, sticky="nsew") 
        Button( 
            f, text='OK', command=self.ok 
            ).grid(column=0, row=2, sticky="s") 
        self.folderlist.bind("<Double-1>", lambda e: self.ok()) 
        f.pack(fill=BOTH, expand=Y) 
 
    def ok(self): 
        if len(self.folderlist.curselection()) != 0: 
            self.result = self.folderlist.get(self.folderlist.curselection()[0]) 
            self.top.protocol('WM_DELETE_WINDOW', None) 
            self.top.destroy() 
 
    def cancel(self): 
        self.top.destroy() 
 
TkGui() 
mainloop() 

代码在 selector = FolderSelection(self.root, ('foo', 'bar')) 行停止,然后在您关闭对话框后继续。