Skip to main content
 首页 » 编程设计

python之如何根据按钮点击无条件地重新运行一个python程序

2024年09月07日7mayingbao

在我的程序执行结束时,我希望出现一条弹出消息,其中有一个可以重新运行程序的按钮。显然,我将设置一个按钮在单击时调用的函数,这样

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) 

请您参考如下方法:

我建议您使用 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()