1

I've written the following code by taking reference from this question

from tkinter import *

def main():
    def hide_me(event):
        event.widget.pack_forget()

    root = Tk()
    btn=Button(root, text="Click")
    btn.bind('<Button-1>', hide_me)
    btn.pack()
    btn2=Button(root, text="Click too")
    btn2.bind('<Button-1>', hide_me)
    btn2.pack()
    btn3=Button(root,text="reload",command=main)
    btn3.pack()
    root.mainloop()

main()

but what I want is when I hit that reload button program will restart from beginning in the same window but it's starting in the new window. And when I've not declared root inside main then it'll restart with a chain of reload buttons.

enter image description here

please help. Thanks In advance.

Aditya
  • 533
  • 3
  • 11
Ashish Dogra
  • 593
  • 4
  • 13

2 Answers2

1

It would be better to implement this as a class with a top-level Tk() window. This way you can keep one reference to the window throughout its lifecycle. On reload, call pack_forget() on all widgets within the window and then repack by a call to main.

This may help:

from tkinter import *

class UI:
    def __init__(self):
        self.root = Tk()

    def hide_me(self, event):
        event.widget.pack_forget()

    def main(self):
        self.btn=Button(self.root, text="Click")
        self.btn.bind('<Button-1>', self.hide_me)
        self.btn.pack()
        self.btn2=Button(self.root, text="Click too")
        self.btn2.bind('<Button-1>', self.hide_me)
        self.btn2.pack()
        self.btn3=Button(self.root,text="reload",command=self.reload)
        self.btn3.pack()
        self.root.mainloop()

    def reload(self):
        self.btn.pack_forget()
        self.btn2.pack_forget()
        self.btn3.pack_forget()
        self.main()

if __name__ == "__main__":
    ui = UI()
    ui.main()
Anoop R Desai
  • 712
  • 5
  • 18
1

You can use root.destroy() method destroy the old tkinter root window and reinitialize your App class.

Please refer the following code:

import tkinter as tk
from tkinter import ttk

class App(object):
    def __init__(self):
        self.root = tk.Tk()
        self.setup()

    def setup(self):
        self.btn = ttk.Button(self.root, text="click")
        self.btn.bind('<Button-1>', self.hide_me)
        self.btn.pack()

        self.btn2 = ttk.Button(self.root, text="Click too")
        self.btn2.bind('<Button-1>', self.hide_me)
        self.btn2.pack()

        self.btn3 = ttk.Button(self.root, text="reload", command=self.restart)
        self.btn3.pack()

    def hide_me(self, event):
        event.widget.pack_forget()

    def restart(self):
        self.root.destroy()
        self.__init__()

def main():
    App()
    tk.mainloop()

if __name__=="__main__":
    main()
Aditya
  • 533
  • 3
  • 11