如何在tkinter中从父框架清除/更新子小部件中的绘图?
我想知道如何清空一个在tkinter中属于某个框架的画布上的图形。我的问题是,这个操作发生在一个叫show()的函数里,而这个函数是在创建框架的不同类中。show()的想法是,它会被多次调用,而不是每次调用show()时都销毁这个小部件并重新创建所有内容,我希望能够清空或更新这个画布里的图形,同时保留这个小部件。
也许用伪代码来解释会更容易理解:
class A():
def__init__(self, master):
sframe = Frame(master)
sframe.pack(side=RIGHT)
f = Figure(figsize=(3,2), dpi=100)
a = f.add_subplot(122);
# initially plots a sine wave
t = arange(0.0, 1, 0.01);
s = sin(2*pi*t);
a.plot(t,s);
canvas = FigureCanvasTkAgg(f, master=sframe)
canvas.show()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
# now i create the other object that will call show()
data_obj = B(sframe)
class B():
...
show(self, frame):
_wlist = frame.winfo_children()
for item in _wlist:
item.clear() # or something like this
# and then re-plot something or update the current plot
代码的最后部分是我遇到一些问题的地方。我不太确定如何清空框架中的小部件。我怎么知道它是什么类型的小部件,如何清空或更新它呢?我得到了:
*** AttributeError: Canvas instance has no attribute 'clear'
任何想法都非常欢迎。非常感谢!
1 个回答
0
我没有直接清空框架中的子元素(这个子元素是一个画布,使用winfo_class()可以查看),而是把图形的坐标轴传递到框架中,同时也传递了画布。
在A类中:
frame.canvas = canvas
frame.ax = a
然后在B类中,我们通过框架来清空坐标轴,更新它并显示画布:
self.sframe.ax.clear()
self.sframe.ax.plot(newline)
self.sframe.canvas.show()
如果你知道通过框架的子元素来访问坐标轴的方法,请告诉我...