vojtam
vojtam

Reputation: 1245

How to open the initial window in tkinter again?

I have a following question. I want to make a button in tkinter that will delete existing changes and the window will looks like the initial window. This is my initial Window 1:

enter image description here

This is how the window looks like when I click on the first two buttons, Window 2:

enter image description here

Now I would like to click on the "Zpět" button and I want to see Window 1 again. Here is my code:

import tkinter as tk

root = tk.Tk()
home_frame = tk.Frame(root)
home_frame.grid(row=0, column=0, sticky="news")

def raise_new_payment():
    tk.Label(text=f"Stav bilance k 2021-09-09").grid()


def back():
    """I would like to this function to clean everything."""
    tk.Label().destroy()

platba = tk.Button(
    home_frame,
    text="Zadej novou platbu",
    command=lambda: raise_new_payment(),
)
platba.pack(pady=10)

zpet = tk.Button(
    home_frame,
    text="Zpět",
    command=back,
)
zpet.pack(pady=10)

I don't know how to use the back() function. I tried to delete the tk.Label as created in raise_new_payment(), but it did not work. Can you help me please? Thanks a lot.

Upvotes: 0

Views: 82

Answers (1)

acw1668
acw1668

Reputation: 46678

I would suggest you create the label once and don't call .pack() on it first, i.e. it is not visible initially.

Then update it inside raise_new_payment() and call .pack() to show it.

You can call .pack_forget() to hide it again inside back().

import tkinter as tk

root = tk.Tk()
home_frame = tk.Frame(root)
home_frame.grid(row=0, column=0, sticky="news")

def raise_new_payment():
    # update label and show it
    lbl.config(text=f"Stav bilance k 2021-09-09")
    lbl.pack()

def back():
    # hide the label
    lbl.pack_forget()

platba = tk.Button(
    home_frame,
    text="Zadej novou platbu",
    command=lambda: raise_new_payment(),
)
platba.pack(pady=10)

zpet = tk.Button(
    home_frame,
    text="Zpět",
    command=back,
)
zpet.pack(pady=10)

# create the label and initially hide it
lbl = tk.Label(home_frame)

root.mainloop()

Upvotes: 1

Related Questions