6

I am wondering on how I can create a restart button that once clicked, can restart the entire script. What I thought was that you destroy the window then un-destroy it but apparently there is no un-destroy function.

j_4321
  • 14,026
  • 2
  • 31
  • 53
NeelJ 83
  • 129
  • 1
  • 2
  • 5

3 Answers3

17

I found a way of doing it for a generic python program on this website: https://www.daniweb.com/programming/software-development/code/260268/restart-your-python-program. I wrote an example with a basic tkinter GUI to test it:

import sys
import os
from tkinter import Tk, Label, Button

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)

root = Tk()

Label(root, text="Hello World!").pack()
Button(root, text="Restart", command=restart_program).pack()

root.mainloop()
j_4321
  • 14,026
  • 2
  • 31
  • 53
1

The following solution works as well but is quite harsh, i.e. the entire environment is lost.

# kills the whole application and starts a fresh one
def restart():
    root.destroy()
    root = Tk()
    root.mainloop()
Elder Druid
  • 496
  • 4
  • 10
0

I would Like to Use this Function:-

First of All Import os Module

import os

Then Use this Code:-

# Restarts the Whole Window    
def restart():
    root.destroy()
    os.startfile("main.py")

Or if You want no console behind then Simply Change the extension of the file to .pyw

And Run this Code:-

# Restarts the Whole Window    
def restart():
    root.destroy()
    os.startfile("main.pyw")