Tkinter-隐藏或退出并返回一个窗口

时间:2018-01-24 03:46:12

标签: python tkinter hide show

我正试图隐藏我的窗口并在之前打开时显示它。

为此,我正在使用一个全局变量,但这个行为并不像我想要的那样。

例如,当我从窗口返回并返回时,我的变量是False而不是我期望的True。

我正在使用带有Tkinter的Python 3.6而这里是代码。

如果有人,可以向我解释为什么这样做或我做错了什么,这对你很好。感谢。

我知道this blog正在展示一种方法,但我想了解为什么这种方式不起作用,谢谢。

from tkinter import * 

def quit_window():  
   window.destroy()
   opened = False
   Main()



def return_main():  
    window.withdraw()
    opened = True
    print(opened)
    Main()

def launch():
    global opened, window
    print(opened)
    if opened == True:
        window.update()
        window.deiconify()
        main.destroy()
    else:
        window = Tk() 
        breturn = Button(window, text="Return", command=return_main).pack()
        bquit = Button(window, text="Quit", command=quit_window).pack() 
        main.destroy()
        window.mainloop()



def Main():  
    global main
    print(opened)
    main = Tk()  
    bopen = Button(main, text="Open", command=launch).pack() 
    main.mainloop()

opened = False 
Main()  

1 个答案:

答案 0 :(得分:0)

您忘记在global openedquit_window函数中添加return_main。因此,当您单击返回按钮时,您的全局变量opened不会更改,只会更改return_main函数中的本地变量main

此外,每次显示window时我都不会发现需要销毁main,因为你在两者之间来回走动。所以我的建议是保留window并在不需要时撤回它。在这种情况下,Toplevel将是main from tkinter import * def quit_window(): global opened window.destroy() opened = False main.deiconify() def return_main(): global opened window.withdraw() opened = True print(opened) main.deiconify() def launch(): global opened, window print(opened) main.withdraw() # withdraw main instead of destroying it if opened == True: window.deiconify() else: window = Toplevel(main) breturn = Button(window, text="Return", command=return_main).pack() bquit = Button(window, text="Quit", command=quit_window).pack() main = Tk() bopen = Button(main, text="Open", command=launch).pack() opened = False main.mainloop() # call mainloop only for main ,代码为:

pointerevent