[英]Deleting matplotlib plot /tkinter canvas from window
I was wondering how you can completely delete a plot from a tkinter window.我想知道如何从 tkinter 窗口中完全删除绘图。
Assuming i would have a tkinter project like the following:假设我会有一个像下面这样的 tkinter 项目:
import tkinter as tk
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
data1 = {'Country': ['US','CA','GER','UK','FR'],
'GDP_Per_Capita': [45000,42000,52000,49000,47000]
}
df1 = DataFrame(data1,columns=['Country','GDP_Per_Capita'])
root= tk.Tk()
figure1 = plt.Figure(figsize=(6,5), dpi=100)
ax1 = figure1.add_subplot(111)
bar1 = FigureCanvasTkAgg(figure1, root)
bar1.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH)
df1 = df1[['Country','GDP_Per_Capita']].groupby('Country').sum()
df1.plot(kind='bar', legend=True, ax=ax1)
ax1.set_title('Country Vs. GDP Per Capita')
def close_plot():
plt.close(figure1)
button_delete = Button(root, text='Delete', command = lambda: close_plot()).place(height=30, width = 100, rely=0.02, relx = 0.4)
root.mainloop()
I veen trying to use matplotlib.pyplot.close within a button but it doens't seem to work.我一直试图在按钮内使用 matplotlib.pyplot.close 但它似乎不起作用。 Anyone have a clue how to get rid of this plot.
任何人都知道如何摆脱这个阴谋。
Thank you very much!非常感谢!
Your figure is embedded in a tkinter
widget.您的图形嵌入在
tkinter
小部件中。 You need to keep a reference to that widget, and use its methods to add/remove it from the tkinter window: Here we use pack_forget()
: the widget is removed from the window, but still exists, and could be reused later.您需要保留对该小部件的引用,并使用其方法在
pack_forget()
窗口中添加/删除它:这里我们使用pack_forget()
:小部件从窗口中删除,但仍然存在,并且可以稍后重用。
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def remove_plot():
w.pack_forget() # here you remove the widget from the tk window
# w.destroy()
if __name__ == '__main__':
# data
x, y = [1, 2, 3, 4], [1, 4, 9, 16]
# matplotlib stuff
figure1 = plt.Figure(figsize=(6, 5), dpi=100)
ax1 = figure1.add_subplot(111)
ax1.plot(x, y)
ax1.set_title('Country Vs. GDP Per Capita')
# tkinter stuff
root = tk.Tk()
bar1 = FigureCanvasTkAgg(figure1, root)
w = bar1.get_tk_widget()
w.pack(side=tk.LEFT, fill=tk.BOTH) # here you insert the widget in the tk window
button_delete = tk.Button(root, text='Remove Plot', command=remove_plot)
button_delete.place(height=30, width=100, rely=0.02, relx=0.4) # place is an odd choice of geometry manager, you will have to adjust it every time the title changes
root.mainloop()
Alternatively, if you don't need that figure any longer, you could use w.destroy
(commented line) to destroy the widget.或者,如果您不再需要该图,您可以使用
w.destroy
(注释行)来销毁小部件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.