如何清除或覆盖 tkinter 画布?



下面的代码显示了我目前正在处理的tkinter GUI的一个页面。

我希望"清除绘图字段"按钮所做的是它所说的:清除画布,因为如果我再次绘制,新绘图将打包在下面。

或者:如何覆盖现有的情节,以便摆脱按钮本身?

class PlotPage(tk.Frame):
"""Page containing the matplotlib graphs"""
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = ttk.Label(self, text="PlotPage", font=LARGE_FONT)
label.pack(pady=5)
button1 = ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage))
button1.pack(pady=5)
buttonPlot = ttk.Button(self, text="Show Plot", command=self.plot)
buttonPlot.pack(pady=5)
buttonClear = ttk.Button(self, text="Clear Plot Field", command=lambda: controller.show_frame(PlotPage))
buttonClear.pack(pady=5)
def plot(self):
"""generate a simple matplotlib graph for multiple profiles"""
f = Figure(figsize=(8,4), dpi=100)   
a = f.add_subplot(111)
for profile in listofProfiles:
X_list=profile.indexList
Y_list=profile.VL_List
[...] Some lines related to plotting [...]
a.plot(X_list, Y_list, lw=0.3,)
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
print("Stuff has been plotted")
def clearPlotPage(self):
"""cleares the whole plot field"""     
# ???
print("Plot Page has been cleared")

简单地谷歌搜索"clear tkinter canvas"让我得到了这个,这个,这个和这个。

简短回答:调用canvas.delete('all')将清除整个画布。

我会destroy()画布,然后重新运行plot().为此,您需要canvas像这样self.canvas这样的类属性。现在我们有一个类属性,您的任何方法都可以毫无问题地使用self.canvas

看看我从你的问题修改的这段代码,如果你有任何问题,请告诉我。

class PlotPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.canvas = None
label = ttk.Label(self, text="PlotPage", font=LARGE_FONT)
label.pack(pady=5)
button1 = ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage))
button1.pack(pady=5)
buttonPlot = ttk.Button(self, text="Show Plot", command=self.plot)
buttonPlot.pack(pady=5)
buttonClear = ttk.Button(self, text="Clear Plot Field", command=lambda: controller.show_frame(PlotPage))
buttonClear.pack(pady=5)
def plot(self):
if self.canvas == None:
f = Figure(figsize=(8,4), dpi=100)   
a = f.add_subplot(111)
for profile in listofProfiles:
X_list=profile.indexList
Y_list=profile.VL_List
# [...] Some lines related to plotting [...]
a.plot(X_list, Y_list, lw=0.3,)
self.canvas = FigureCanvasTkAgg(f, self)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2TkAgg(self.canvas, self)
toolbar.update()
self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
print("Stuff has been plotted")
else:
print("Plot already plotted please clear first")
def clearPlotPage(self):
self.canvas.destroy()
self.canvas = None
self.plot()
print("Plot Page has been cleared")

对于仍在处理 AttributeError 的人:"FigureCanvasTkAgg"对象没有属性"destroy"。

我通过创建一个"虚拟"容器框架来包装可以销毁的 FigureCanvas 来解决这个问题,进而破坏 FigureCanvas。

最新更新