首页 > 解决方案 > 如何再次在 tkinter 中打开初始窗口?

问题描述

我有以下问题。我想在 tkinter 中创建一个按钮,该按钮将删除现有更改,并且窗口看起来像初始窗口。这是我的初始窗口 1:

在此处输入图像描述

这是我单击前两个按钮 Window 2 时窗口的样子:

在此处输入图像描述

现在我想点击“Zpět”按钮,我想再次看到 Window 1。这是我的代码:

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)

我不知道如何使用该back()功能。我试图删除在 中创建的 tk.Label raise_new_payment(),但它不起作用。你能帮我吗?非常感谢。

标签: pythontkinter

解决方案


我建议你创建标签一次,不要.pack()先调用它,即它最初是不可见的。

然后在里面更新它raise_new_payment()并调用.pack()显示它。

你可以再打电话.pack_forget()把它藏在里面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()

推荐阅读