我想知道如何创建一个重启按钮,一旦点击就可以重新启动整个脚本。我的想法是销毁窗口然后再取消销毁,但显然没有取消销毁的功能。
我在这个网站上找到了一种用于通用 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()
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")
# kills the whole application and starts a fresh one
def restart():
root.destroy()
root = Tk()
root.mainloop()