Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart program tkinter

Tags:

python

tkinter

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.

like image 388
NeelJ 83 Avatar asked Jan 14 '17 22:01

NeelJ 83


2 Answers

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()
like image 58
j_4321 Avatar answered Oct 11 '22 07:10

j_4321


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()
like image 44
Elder Druid Avatar answered Oct 11 '22 06:10

Elder Druid