Tkinter窗口重置问题:如何实现按钮点击恢复至初始窗口状态
Hey there! I see the issue you're running into—let's break this down and fix it step by step.
The Core Problem
When you create the label in raise_new_payment(), you don't store a reference to it:
tk.Label(text=f"Stav bilance k 2021-09-09").grid()
This means the label gets rendered, but you have no way to target it later in your back() function. The code you tried (tk.Label().destroy()) just creates a new empty label and immediately destroys it—this has zero effect on the actual label you want to remove.
Solution 1: Track the Dynamic Label with a Reference
We can use a global variable to keep track of the label we create, so we can destroy it when needed. Here's the adjusted code:
import tkinter as tk root = tk.Tk() home_frame = tk.Frame(root) home_frame.grid(row=0, column=0, sticky="news") # Global variable to hold our dynamic label reference dynamic_label = None def raise_new_payment(): global dynamic_label # First, clean up any existing label before creating a new one if dynamic_label is not None: dynamic_label.destroy() # Create the label and save its reference dynamic_label = tk.Label(text=f"Stav bilance k 2021-09-09") dynamic_label.grid() def back(): global dynamic_label # Destroy the label if it exists, then reset the variable if dynamic_label is not None: dynamic_label.destroy() dynamic_label = None 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) root.mainloop()
Solution 2: Use a Dedicated Frame for Dynamic Content (Better for Scalability)
If you plan to add more dynamic elements (like entries, buttons, or other widgets) later, wrapping them in a dedicated frame is a cleaner approach. This lets you clear all dynamic content at once without tracking individual widgets:
import tkinter as tk root = tk.Tk() home_frame = tk.Frame(root) home_frame.grid(row=0, column=0, sticky="news") # Create a frame to hold all dynamic content dynamic_content_frame = tk.Frame(root) dynamic_content_frame.grid(row=1, column=0, sticky="news") def raise_new_payment(): # Clear any existing content in the dynamic frame first for widget in dynamic_content_frame.winfo_children(): widget.destroy() # Add new content to the dynamic frame tk.Label(dynamic_content_frame, text=f"Stav bilance k 2021-09-09").pack() def back(): # Destroy all widgets in the dynamic frame to reset to initial state for widget in dynamic_content_frame.winfo_children(): widget.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) root.mainloop()
This second method is more flexible—it works seamlessly even as you expand your app with more dynamic UI elements, no extra tracking required.
内容的提问来源于stack exchange,提问作者vojtam

