0

Need your help lads and lasses!

I made a very simple hangman game with a GUI in Tkinter and created a button event that calls the following function to restart the game. This works fine as a Python script but does not work when converting script to .exe with Pyinstaller. ('Window" here is the root Tkinter window)


def restart_func():
    window.destroy()
    os.startfile("main.py")
    return

Any ideas why or alternative way of doing this would be much appreciated.

2
  • 1
    you would be better making it so that you could restart your game without destroying the window....... Commented Oct 25, 2022 at 7:19
  • i agree that the only reason a restart button would map to destroying your window then running your executable again is when you are just scratching that application off your to-do list and the next item in your to-do list is to delete that application. Commented Oct 25, 2022 at 7:28

1 Answer 1

1

you should recreate your window and initialize it the same way you originially did.

def restart_func():
    global window
    window.destroy()
    window = tk.Tk()
    run_gui_initialization_function()

this is usually why some applications prefer OOP instead of functional programming, as there is usually no global state in OOP programming, while for functional programming, your run_gui_initialization_function should reinitialize all of your global state variables again.

an alternative way people do this is as follows

def main():
    # do main app here

if __name__ == "__main__":
    main()

this way you just need to run main() again after deleting your window if you ever need to restart your app.

Edit: okay, here's an easier to implement but too messy way to do this, you can start a detached version of your application from your executable ... but this is the wrong way to restart an application, and it might fail in some cases.

from subprocess import Popen
import sys
def restart_func():
    window.destroy()
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        Popen(sys.executable,start_new_session=True)  # if running as executable
    else:
        os.startfile("main.py")  # if running as python script
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks all. Let me play around with this a bit and see what works best.

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.