问题(故事):
我在一个条目小部件里写,然后我按下一个按钮,窗口中出现一个新标签,上面有我输入的文字 . 然后我按下一个不同的按钮,期望的结果是生成的标签消失,但是,我收到一条错误消息 .
我为什么要这样做?
我想创建一个接口来进行SQL查询,我正在尝试实现的过程是:
-
用户在条目小部件中输入字符串 .
-
用户按"search"按钮执行查询 .
-
界面返回结果 . (我使用
LabelFrame
和Frame
小部件实现了这一点) . -
用户按下"clear"按钮,生成的所有小部件消失,界面已准备好进行新查询 .
不隐藏的标签(代码):
from tkinter import *
root = Tk()
pacienteLabel = Label(text="Paciente: ")
pacienteLabel.grid()
pacienteEntry = Entry()
pacienteEntry.grid()
profesionalLabel = Label(text="Profesional: ")
profesionalLabel.grid()
profesional = StringVar()
# Here I capture the string that I want to show:
profesionalEntry = Entry(textvariable=profesional)
profesionalEntry.grid()
def ver():
# This label is generated without problems:
newLabel = Label(text="hola profesional: {}".format(profesional.get()))
newLabel.grid()
# When I was trying to figure out what was happening I added this:
print(newLabel)
# And the output is:
# .!label4
# I have read through documentation why is this but I couldn't find why.
buscarButton = Button(text="Buscar", command=ver)
buscarButton.grid()
def borrar():
# After that I saw the previous output from print was obvious why the
# next line don't work:
newLabel.grid_forget()
borrarButton = Button(text="Borrar", command=borrar)
borrarButton.grid()
root.mainloop()
下图显示了错误和GUI:
最后,我在这里读到了什么:
最后,如果您正在阅读这个问题,感谢您的时间!
1 回答
您可以将
global newLabel
添加为def ver():
的第一行,但这样您只能隐藏最后创建的标签 . 原因是您没有为前一个标签对象留下任何参考,但它们仍然存在,但它们不能很容易地被引用 . 相反,我将提供一个答案:可以对窗口小部件执行各种操作(标签是窗口小部件),只要它们具有有效的引用(您的
newLabel
引用被覆盖) . 它不允许用户设置新标签的文本button_that_creates_labels
,button_that_hides_labels
,entry
.button_that_hides_labels
以递归方式隐藏最后添加的标签:但是,如果你想破坏和删除而不是隐藏,我的实现会简单得多: