Python 在tkinter上清除并绘制mathplot图形
我需要一些关于我当前代码的帮助。我想通过tkinter创建一个窗口,并在之前由matplotlib创建的画布中显示一个绘图。这一点我还没有达到。我的问题是我想通过点击一个按钮来清除这个画布。为了清除画布,我想在用绘图填充画布之前对其进行初始化 所以我的问题是:如何在已创建的画布中填充绘图 下面你可以找到一个小代码,显示我的艺术状态Python 在tkinter上清除并绘制mathplot图形,python,matplotlib,tkinter,tkinter-canvas,Python,Matplotlib,Tkinter,Tkinter Canvas,我需要一些关于我当前代码的帮助。我想通过tkinter创建一个窗口,并在之前由matplotlib创建的画布中显示一个绘图。这一点我还没有达到。我的问题是我想通过点击一个按钮来清除这个画布。为了清除画布,我想在用绘图填充画布之前对其进行初始化 所以我的问题是:如何在已创建的画布中填充绘图 下面你可以找到一个小代码,显示我的艺术状态 from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
def plot():
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
output = FigureCanvasTkAgg(fig, master = window)
output.draw()
# placing the canvas on the Tkinter window
output.get_tk_widget().pack()
def clear_plot():
canvas.delete('all')
# the main Tkinter window
window = Tk()
# setting the title
window.title('Plotting in Tkinter')
# dimensions of the main window
window.geometry("700x700")
canvas = Canvas(window, width=500, height=500)
canvas.pack()
# button that displays the plot
plot_button = Button(master = window, command = plot, height = 2, width = 10, text = "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 canvas的
destroy
方法销毁小部件本身来清除画布(注意,您不能销毁mathplot画布本身,因为它没有任何类似destroy的方法)
要在tkinter画布上放置数学绘图画布,只需将master设置为canvas
对象(output=FigureCanvasTkAgg(图,master=canvas)
)
(这是您更正的代码)
或者你可以用
def clear_plot():
global output
if output:
output.get_tk_widget().destroy()
output = None
这里的输出是您的FigureCastKagg
实例,供其他希望实现此目标的人使用。您只需要暂时隐藏绘图输出。获取\tk\u小部件().pack\u忘记()
并再次显示它输出。获取\tk\u小部件().pack()
更新
output.get_tk_widget()
返回用于实现FigureCanvasTkAgg的tk小部件,这意味着您还可以使用
帆布。因此,
output.get_tk_widget().delete('all')
也可以您是否只想通过按下按钮来清除绘图?是的,在我点击“绘图”后,图形应该显示在我创建的画布中的按钮上方(而不是在新画布窗口中的按钮下方),然后点击“清除”我希望有一个清晰的画布后,再次启动程序
def clear_plot():
global output
if output:
output.get_tk_widget().destroy()
output = None