重新启动 tkinter 程序

7

我想知道如何创建一个重启按钮,一旦点击就可以重新启动整个脚本。我的想法是销毁窗口然后再取消销毁,但显然没有取消销毁的功能。


看起来像是 https://dev59.com/CUfRa4cB1Zd3GeqP6ykB 的重复。 - Grisha Levit
3
可能是重置主GUI窗口的重复问题。 - Grisha Levit
3个回答

18

我在这个网站上找到了一种用于通用 Python 程序的方法:https://www.daniweb.com/programming/software-development/code/260268/restart-your-python-program。我编写了一个带有基本 tkinter GUI 的示例以进行测试:

import sys
import os
from tkinter import Tk, Label, Button

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)

root = Tk()

Label(root, text="Hello World!").pack()
Button(root, text="Restart", command=restart_program).pack()

root.mainloop()

1
我想使用这个函数:-
首先导入os模块
import os

然后使用这段代码:

# Restarts the Whole Window    
def restart():
    root.destroy()
    os.startfile("main.py")

如果您不想在后台使用控制台,则可以将文件扩展名更改为 .pyw

然后运行此代码:

# Restarts the Whole Window    
def restart():
    root.destroy()
    os.startfile("main.pyw")

1
以下解决方案同样有效,但是比较严厉,即整个环境都会丢失。
# kills the whole application and starts a fresh one
def restart():
    root.destroy()
    root = Tk()
    root.mainloop()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接