[英]How to erase the contents of a Frame
I have a Frame
which is filled up with several Label
. 我有一个装有几个
Label
的Frame
。 The text in all the Label
is recalculated on a regular basis and I would like to erase everything in the Frame
before. 所有
Label
的文本都会定期重新计算,我希望之前删除Frame
所有内容。
Initially I thought that it would be enough to replace the text of the Label
: 最初,我认为替换
Label
的文本就足够了:
import Tkinter as tk
class MyApp():
def __init__(self):
self.counter = 0
self.root = tk.Tk()
self.frame = tk.Frame(self.root)
self.frame.grid(row=0, column=0) # typo edited following the answer
self.root.bind('q', self.toggle)
def toggle(self, event):
self.counter += 1
if self.counter % 2 == 0:
text = "hello {}".format(self.counter)
bg = "green"
else:
text = "very long text, longer than hello {}".format(self.counter)
bg = "blue"
# the tk.Label call is not assigned to a variable on purpose
tk.Label(self.frame, text=text, bg=bg).grid(row=0, column=0)
app = MyApp()
app.root.mainloop()
The text is not replaced, though, but the longer one stays: 文本不会被替换,但是保留的时间更长:
How can I erase the contents of the Frame without erasing each of its elements? 如何在不删除框架的每个元素的情况下擦除框架的内容?
Please note that the tk.Label
call is not assigned a variable to, I have several Label
and do did not need to keep track of them, once they are displayed. 请注意,
tk.Label
调用未分配变量,我有多个Label
并且在显示它们后无需跟踪它们。 I could, I guess, keep a list of all the Label
and .grid_forget()
them but if there is a simpler solution it would bring a cleaner code. 我可以保留所有
Label
和.grid_forget()
的列表,但是如果有更简单的解决方案,它将带来更简洁的代码。
Since you are always using the same label, you can create it in your __init__
method and then configure it in you callback: 由于您始终使用相同的标签,因此可以在
__init__
方法中创建它,然后在回调中对其进行配置:
def __init__(self):
# ...
self.frame = tk.Frame(self.root).grid(row=0, column=0)
self.label = tk.Label(self.frame)
self.label.grid()
self.root.bind('q', self.toggle)
def toggle(self, event):
self.counter += 1
# ...
# the tk.Label call is not assigned to a variable on purpose
self.label.config(text=text, bg=bg)
UPDATE: Since you don't want to use any variable for the label, you can destroy all the children of the frame: 更新:由于您不想为标签使用任何变量,因此可以销毁框架的所有子部件:
def toggle(self, event):
# ...
for children in self.frame.winfo_children():
children.destroy()
tk.Label(self.frame, text=text, bg=bg).grid(row=0, column=0)
Keep in mind that the call to grid()
returns None
, so in your original example the variable self.frame
does not contain the widget reference: 请记住,对
grid()
的调用返回None
,因此在您的原始示例中,变量self.frame
不包含小部件引用:
def __init__(self):
self.counter = 0
self.root = tk.Tk()
self.frame = tk.Frame(self.root)
# WRONG
# self.frame = tk.Frame(self.root).grid(row=0, column=0)
# RIGHT
self.frame.grid() # row=0, column=0 comes by default
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.