清除包含Matplotlib图形的tkinter画布

2024-06-28 11:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个用户界面,用户必须将数据放入帧中,然后单击一个按钮创建Matplotlib界面。我可以让它工作,我的图表显示在工具栏上。在

但当我再次单击按钮时,我无法让另一个图形消失。我看到我可以使用.delete来清除画布。将它作为函数的第一行将给我“在赋值之前使用的‘canvas’”。我试着把它写成全局,但似乎也没用。在

以下是代码中有问题的部分:

def graphiqueMatplot():
    #Not included: computation of the coordinates xS, yS,...
    f = Figure(figsize=(5,5), dpi=100)
    canvas = FigureCanvasTkAgg(f, master=courbe)
    a = f.add_subplot(111)
    a.plot(xS, yS)
    a.plot(xT, yT)
    a.plot(xL, yL)

    a.axis('tight')

    canvas.show()
    canvas.get_tk_widget().pack(side='top', fill=Y, expand=1)
    toolbar = NavigationToolbar2TkAgg( canvas, courbe )
    toolbar.update()
    canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

#Main Program
cadreSimulation=Labelframe(root, text='Simulation')
courbe=Canvas(cadreSimulation, height=500, width=500, cursor='trek')

boutonGraphiqueMatplot=Button(cadreSimulation, text='Launch Matplotlib', command=graphiqueMatplot)
boutonGraphiqueMatplot.pack(side='top', fill='x')

courbe.pack()

cadreSimulation.pack(side='left')

你能帮忙吗?谢谢!在

我想补充一点,我是一个编程的乞丐,不是一个以英语为母语的人,所以如果你看到任何关于这些的错误,请不要犹豫告诉我!


Tags: plotmatplotlibtopfill按钮sidepackcanvas
1条回答
网友
1楼 · 发布于 2024-06-28 11:30:29

你有两个主要的选择。在

  1. graphiqueMatplot()函数之外创建FigureCanvasTkAgg对象,让该函数将该对象作为参数,然后让该函数用新图形重新配置画布。在

canvas = FigureCanvasTkAgg(f, master=courbe)
# more canvas creation and packing
...

boutonGraphiqueMatplot=Button(cadreSimulation, text='Launch Matplotlib',
                              command=lambda: graphiqueMatplot(canvas))
...

def graphiqueMatplot(c):
    f = Figure(figsize=(5,5), dpi=100)
    c.config(figure=f) # this is how tkinter objects are reconfigured,
                       # but it may be different for FigureCanvasTkAgg objects!
    a = f.add_subplot(111)
    # more plotting statements here
  1. 尝试使用delete()函数,捕捉异常:

^{pr2}$

相关问题 更多 >