【问题标题】:How to open a root window, close it and then open another window in tkinter after a few seconds?如何打开一个根窗口,关闭它,然后几秒钟后在 tkinter 中打开另一个窗口?
【发布时间】:2020-09-17 22:58:06
【问题描述】:

我使用 Tkinter 为我的语音助手 Python 脚本制作了一个 GUI。它工作得很好。但我想添加一个动画窗口来显示我使用 After Effects 创建的动画作为应用程序的介绍。我希望它在没有默认关闭(x)、最大化和最小化按钮的情况下打开。窗口应该一直停留到动画完成,然后它会消失。然后主窗口将正常打开以启动 GUI。为了禁用关闭、最大化和最小化按钮,我使用了root.overrideredirect(True) 方法。但是我不能像上面提到的那样一个接一个地同时打开两个窗口。如果有人能帮助我解决这个问题,我将非常感激!我已经在一个简单的 GUI 上使用代码对其进行了测试。我正在提供以下代码以帮助解决问题!

from tkinter import *
import time

root = Tk()
root.geometry('500x300')
root.overrideredirect(True) # To disable the default Window decoration
time.sleep(5) # Assuming that the animation runs for 5 seconds
root.destroy() # This window destroys after being on screen for 5 seconds
root.mainloop()

root2 = Tk() # After the previous window is destroyed, this window opens up. Assume that this is the main window
root2.geometry('500x300')
root.mainloop()

请帮帮我!

【问题讨论】:

    标签: python windows user-interface tkinter


    【解决方案1】:

    你称之为“动画窗口”的东西实际上叫做“splash”。有一种方法可以做你想做的事。您需要为应用程序(一个 Tk 实例)创建一个根窗口,然后您应该隐藏(root.withdraw())它。现在为启动创建一个 Toplevel,等待 5 秒,将其销毁,然后再次显示 (root.deiconify()) Tk 窗口。

    注意:time.sleep(5) 不应该永远与 Tkinter 一起使用,而是使用 root.after(ms, func)

    from tkinter import *
    
    
    def show_splash():
        splash = Toplevel()
        splash.geometry('500x300')
        splash.overrideredirect(True) # To disable the default Window decoration
        splash.after(5000, splash.destroy) # This window destroys after being on screen for 5 seconds
        splash.wait_window()
    
    root = Tk()
    root.withdraw()
    show_splash()
    root.deiconify()
    root.mainloop()
    

    PS:过程式编程对于非常复杂的基于 Tkinter 的应用程序来说不是一个好主意。您应该考虑改用 OOP。

    PPS:看看thisthis 的答案。

    【讨论】:

    • 我使用您的代码进行了检查。它在测试代码上运行良好。但我需要确定它是否适用于主要的。完成后我会告诉你的!感谢您的帮助!
    • @SohamChatterjee 我找到了一种更短、更简单、更干净的方法来做你想做的事情,所以我更新了答案中的代码。看看吧。
    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2018-05-02
    • 2020-03-19
    • 2023-01-12
    • 2017-07-16
    • 2018-05-11
    • 2018-05-18
    相关资源
    最近更新 更多