Tkinter 小部件在传递另一个小部件的命令后不会消失



我需要在传递第二个标签的命令(通过按另一个按钮(后立即消失或销毁以前的标签。我不希望小部件落后,只是被一个新的小部件所掩盖,我需要它们完全消失。

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()

目前没有理由让标签消失,你的代码所做的只是在最后一个标签下面打包一个新标签。最好创建一个标签并使用.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()

最新更新