您可以将 global newLabel 添加为 def ver(): 的第一行,但这样您只能隐藏最后创建的标签 . 原因是您没有为前一个标签对象留下任何参考,但它们仍然存在,但它们不能很容易地被引用 . 相反,我将提供一个答案:
“如何使用另一个按钮隐藏使用命令按钮生成的标签?”
可以对窗口小部件执行各种操作(标签是窗口小部件),只要它们具有有效的引用(您的 newLabel 引用被覆盖) . 它不允许用户设置新标签的文本 button_that_creates_labels , button_that_hides_labels , entry . button_that_hides_labels 以递归方式隐藏最后添加的标签:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def create_new_label(parent, widget_list, entry, button):
widget_list.append(tk.Label(parent, text=entry.get()))
widget_list[-1].grid(columnspan=2)
button['command'] = lambda w=widget_list, i=-1, b=button: \
hide_the_last_label(w, i, b)
def hide_the_last_label(widget_list, index, button):
if len(widget_list) >= abs(index):
widget_list[index].grid_remove()
button['command'] = lambda w=widget_list, i=index-1, b=button: \
hide_the_last_label(w, i, b)
def main():
root = tk.Tk()
# This list will contain all widgets objects generated during the
# execution of the lambda expression.
labels = list()
entry = tk.Entry(root)
button_that_hides_labels = tk.Button(root, text="Hide")
# A lambda expression to prevent call the function before the
# button has been pressed.
button_that_creates_labels = tk.Button(root, text="Create",
command=lambda p=root, wl=labels, e=entry, b=button_that_hides_labels\
: create_new_label(p, wl, e, b))
button_that_hides_labels['command'] = lambda w=labels, i=-1, \
b=button_that_hides_labels:hide_the_last_label(w, i, b)
button_that_creates_labels.grid(row=1, column=0)
button_that_hides_labels.grid(row=1, column=1)
entry.grid(row=0, column=0, columnspan=2)
tk.mainloop()
if __name__ == '__main__': main()
但是,如果你想破坏和删除而不是隐藏,我的实现会简单得多:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def create_new_label(parent, widget_list, entry):
widget_list.append(tk.Label(parent, text=entry.get()))
widget_list[-1].grid(columnspan=2)
def remove_the_last_label(widget_list):
if widget_list:
# Here the widget don't show up
widget_list[-1].destroy()
# If the item is not removed from the list, white spaces will remain
# in the window.
del widget_list[-1]
def main():
root = tk.Tk()
labels = list()
entry = tk.Entry(root)
button_that_hides_labels = tk.Button(root, text="Hide")
button_that_creates_labels = tk.Button(root, text="Create",
command=lambda p=root, wl=labels, e=entry: create_new_label(p, wl, e))
button_that_hides_labels['command'] = lambda w=labels: \
remove_the_last_label(w)
button_that_creates_labels.grid(row=1, column=0)
button_that_hides_labels.grid(row=1, column=1)
entry.grid(row=0, column=0, columnspan=2)
tk.mainloop()
if __name__ == '__main__':
main()