【问题标题】:Tkinter Widgets not disappearing after command for another widget is passed传递另一个小部件的命令后,Tkinter 小部件不会消失
【发布时间】:2023-03-31 23:19:01
【问题描述】:

一旦第二个标签的命令通过(通过按下另一个按钮),我需要前一个标签消失或销毁。我不希望小部件落后,只是被新的遮蔽,我需要它们完全消失。

from tkinter import *
root=Tk()
root.geometry('800x600+0+0')
f1=Frame(root, width=700, height=200, bg='green')
f1.pack()
f2=Frame(root, width=700, height=200, bg='yellow')
f2.pack()

def hello():
    l1=Label(f2,text='Hello button pressed', fg='red').pack()
def bye():
    l2=Label(f2,text='Secondly, Bye button pressed', fg='blue').pack()

b1=Button(f1, text='Hello', command=hello).pack()
b2=Button(f1, text='Bye', command=bye).pack()

【问题讨论】:

    标签: python-3.x tkinter widget


    【解决方案1】:

    目前没有理由让标签消失,您的代码所做的只是在最后一个标签下添加一个新标签。您最好创建一个标签并使用.config() 方法更改该标签的文本。

    from tkinter import *
    root=Tk()
    root.geometry('800x600+0+0')
    f1=Frame(root, width=700, height=200, bg='green')
    f1.pack()
    f2=Frame(root, width=700, height=200, bg='yellow')
    f2.pack()
    
    # label to change
    lbl = Label(f2, text='', fg='red')
    lbl.pack()
    
    
    def hello():
        global lbl
        # edit label text
        lbl.config(text='Hello button pressed', fg='red')
    
    
    def bye():
        global lbl
        lbl.config(text='Secondly, Bye button pressed', fg='blue')
    
    
    b1=Button(f1, text='Hello', command=hello).pack()
    b2=Button(f1, text='Bye', command=bye).pack()
    
    root.mainloop()
    

    【讨论】:

    • 效果很好,但是除了 config 方法之外,有没有一种方法可以“销毁”标签(和其他小部件)?我这么问是因为我有几个小部件(按钮、标签、输入框等),我需要“消失”以为其他命令调用的其他小部件铺平道路。它不仅仅是一个标签。代码很小,以上面的标签为例。
    • 使用 .pack_forget() 。这只是“解包”小部件而不是销毁它,因此如果您需要再次打包它,它仍然存在。如果您真的想销毁它以使其无法再次打包,请在小部件上调用 .destroy()。
    猜你喜欢
    • 2015-02-06
    • 2011-04-27
    • 2020-02-22
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2021-09-26
    • 2022-01-04
    相关资源
    最近更新 更多