如何根据按钮点击无条件重新运行python程序?

时间:2018-01-15 16:45:56

标签: python user-interface tkinter

在我的程序执行结束时,我想要一个弹出消息,它有一个可以重新运行程序的按钮。显然,我会设置一个按钮在单击时调用的功能,如此

def restart():
    **python command that makes the whole program restart**

然后我会将此功能附加到以下按钮:

B1 = ttk.Button(popup, text='Restart program', width=17, command=lambda: restart())

有这样的命令吗?

快速注意:我找到了答案,但它不起作用,现在是:

os.execl(sys.executable, sys.executable, *sys.argv)

2 个答案:

答案 0 :(得分:1)

这可能是一种过于简单的方法,但是说你现有的程序看起来像:

def my_app():
    # Code goes here

if __name__ == "__main__":
    my_app()

而是像这样包装:

def my_app():
    print("App is running!")
    # Your app code goes here
    print("App is exiting!")
    # On exit popup a prompt where selecting 'restart' sets restart_on_exit to True
    # Replace input() with a popup as required
    if input("Type y <return> to restart the app! ").lower() == "y":
        return True

if __name__ == "__main__":
    restart_on_exit = True
    while restart_on_exit:
        restart_on_exit = my_app()

如果在循环重复之前弹出窗口将my_app设置为restart_on_exit,那么代码将循环,一遍又一遍地运行True

答案 1 :(得分:1)

我建议您使用subprocess模块重新执行旨在替换旧os.exec...()组函数的程序。

这是一个如何使用它重新启动脚本的可运行(即完整)示例,该脚本在Windows上使用Python 3.6.4进行了测试:

import os
import subprocess
import sys
import tkinter as tk
import traceback

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack(fill="none", expand=True)  # Center the button.
        self.create_widgets()

    def create_widgets(self):
        self.restart_btn = tk.Button(self, text='Restart', command=self.restart)
        self.restart_btn.grid()

    def restart(self):
        command = '"{}" "{}" "{}"'.format(
            sys.executable,             # Python interpreter
            __file__,                   # argv[0] - this file
            os.path.basename(__file__), # argv[1] - this file without path
        )
        try:
            subprocess.Popen(command)
        except Exception:
            traceback.print_exc()
            sys.exit('fatal error occurred rerunning script')
        else:
            self.quit()


app = Application()
app.master.title('Restartable application')
app.mainloop()