[英]Using tkinter — How to clear FigureCanvasTkAgg object if exists or similar?
Trying to create a tkinter based window that allows user to create a chart on button click, refreshing the chart -- not adding another, each time. 尝试创建一个基于tkinter的窗口,允许用户在按钮单击时创建图表,刷新图表 - 每次都不添加另一个图表。 All without creating a new window.
所有这些都没有创建新窗口。 The idea is click -> create chart, click again -> replace the chart with new chart in same spot.
想法是点击 - >创建图表,再次点击 - >在同一地点用新图表替换图表。 No extra clicks, no extra button to close.
没有额外的点击,没有额外的按钮关闭。 Using matplotlib.backends.backend_tkagg and FigureCanvasTkAgg.
使用matplotlib.backends.backend_tkagg和FigureCanvasTkAgg。 Documentation appears to be virtually non-existent on this.
文档似乎几乎不存在。 Tried various attributes in .get_tk_widget() to see if I could test if it exists already, get a list, etc. Also tried clearing canvas.
尝试.get_tk_widget()中的各种属性,看看我是否可以测试它是否已存在,获取列表等。还尝试清除画布。
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import *
class testme:
def __init__(self,frame1):
self.frame1=frame1
self.button=Button(self.frame1,text="DRAWME",command=self.plot)
self.button1=Button(self.frame1,text="CLEARME",command=self.clearme)
self.button.pack()
self.button1.pack()
def plot(self):
f=Figure(figsize=(5,1))
aplt=f.add_subplot(111)
aplt.plot([1,2,3,4])
self.wierdobject = FigureCanvasTkAgg(f, master=self.frame1)
self.wierdobject.get_tk_widget().pack()
self.wierdobject.draw()
def clearme(self):
self.wierdobject.get_tk_widget().pack_forget()
root=Tk()
aframe=Frame(root)
testme(aframe)
aframe.pack() #packs a frame which given testme packs frame 1 in testme
root.mainloop()
Attached example code almost approximates my goal but it requires a "CLEARME" button (which only works right if "DRAWME" was only clicked once. I just want some kind of if statement that checks if there is a FigureCanvasTkAgg object in the frame already and if so remove it instead of a button click. 附加的示例代码几乎接近我的目标,但它需要一个“CLEARME”按钮(只有“DRAWME”只被点击一次才能正常工作。我只想要某种if语句检查框架中是否有一个FigureCanvasTkAgg对象如果是这样,请删除它而不是单击按钮。
After a number of attempts I concluded I have a fundamental misunderstanding of more than one thing that's going on here. 经过多次尝试,我得出结论,我对这里发生的不止一件事情有一个根本的误解。
For your current setup, just add a try clause at the start of your plot
function. 对于当前的设置,只需在
plot
函数的开头添加一个try子句。
def plot(self):
try:
self.wierdobject.get_tk_widget().pack_forget()
except AttributeError:
pass
f=Figure(figsize=(5,1))
aplt=f.add_subplot(111)
aplt.plot([1,2,3,4])
self.wierdobject = FigureCanvasTkAgg(f, master=self.frame1)
self.wierdobject.get_tk_widget().pack()
self.wierdobject.draw()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.