At the end of my program execution, I want a popup message to appear that has a button which can re-run a program. Obviously, I will have setup a function that the button calls when it is clicked, as such
def restart():
**python command that makes the whole program restart**
Then I would attach this function to the following button:
B1 = ttk.Button(popup, text='Restart program', width=17, command=lambda: restart())
Is there such a command?
Quick note:I found an answer but it doesn't work, here it is:
os.execl(sys.executable, sys.executable, *sys.argv)
I suggest that you use the subprocess
module to re-execute the program which was designed to replace the older os.exec...()
group of functions.
Here's a runnable (i.e. complete) example of how to use it to restart the script, which was tested on Windows with 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()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments