from tkinter import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
def plot():
global output, fig
if fig:
fig.clear()
fig = Figure(figsize=(5, 5), dpi=100)
y = [i ** 2 for i in range(101)]
# adding the subplot
plot1 = fig.add_subplot(111)
# plotting the graph
plot1.plot(y)
# creating the Tkinter canvas
# containing the Matplotlib figure
if output:
output.get_tk_widget().destroy()
output = FigureCanvasTkAgg(fig, master=canvas)
output.draw()
# placing the canvas on the Tkinter window
output.get_tk_widget().pack()
def clear_plot():
global output
print(fig)
if output:
for child in canvas.winfo_children():
child.destroy()
# or just use canvas.winfo_children()[0].destroy()
output = None
# 这样耶OK
def clear_plot_V2():
global output
if output:
output.get_tk_widget().destroy()
output = None
# the main Tkinter window
window = Tk()
output = None
fig = None
# setting the title
window.title('Plotting in Tkinter')
# dimensions of the main window
window.geometry("700x700")
canvas = Canvas(window, width=500, height=500, bg='white')
canvas.pack()
# button that displays the plot
plot_button = Button(master=window, command=plot, height=2, width=10, text="Run Plot")
clear_button = Button(master=window, command=clear_plot, height=2, width=10, text="clear", background="yellow")
# place the button
plot_button.pack()
clear_button.pack()
# run the gui
window.mainloop()
tkinter展示清除matplotlib图
最新推荐文章于 2024-07-20 17:12:48 发布