2

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)
6
  • 1
    Wrap the 'starting method' (main or similar) in another method that either calls it again or exits, depending on the state of a variable set by the restart popup. Commented Jan 15, 2018 at 16:57
  • @match Can you please elaborate because I didn't anything you just said :) Commented Jan 15, 2018 at 16:59
  • Can you please explain the problem you want to solve by restarting in details? Commented Jan 15, 2018 at 17:01
  • I think what @match is saying is to put all of your code in a function: def main(): # all code goes here. Then instead of restart(), the button can just call main(). Commented Jan 15, 2018 at 17:06
  • 1
    Also as an aside, instead of lambda: restart() you can just use restart without parentheses to achieve the same thing. Commented Jan 15, 2018 at 17:08

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

1

This is potentially an over-simple approach, but say your existing program looks something like:

def my_app():
    # Code goes here

if __name__ == "__main__":
    my_app()

Instead wrap it like this:

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()

That way the code will loop, running my_app over and over again, if the popup sets restart_on_exit to True before the loop repeats.

2 Comments

I'm envisaging that my_app is a long running interactive GUI, which will block on the popup to ask about restarting, so a sleep seems unnecessary, but for a short-lived non-interactive method, sure.
I think this is a better approach than restarting entire script, but the code snippets you use could've been better if they were minimal reproducible examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.