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