【问题标题】:Clearing a tkinter canvas containing a Matplotlib graph清除包含 Matplotlib 图的 tkinter 画布
【发布时间】:2015-07-17 00:03:15
【问题描述】:

我正在制作一个用户界面,用户必须将数据放入一个框架中,然后单击一个按钮创建一个 Matplotlib 界面。我能够让它工作,并且我的图表与工具栏一起显示。

但是当我再次单击该按钮时,我无法让其他图表消失。我看到我可以使用 .delete 来清除画布。把它作为函数的第一行会给我“分配前使用的'画布'”。我尝试将其设置为 global,但这似乎也不起作用。

这里是代码有问题的部分:

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')

你能帮忙吗?非常感谢!

我想补充一点,我是一名编程初学者,而不是以英语为母语的人,所以如果你发现任何关于这些的错误,请不要犹豫告诉我!

【问题讨论】:

    标签: python canvas matplotlib tkinter


    【解决方案1】:

    这里有两个主要选项。

    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() 函数,捕获异常:

    def graphiqueMatplot():
        #Not included: computation of the coordinates xS, yS,...
        try:
            delete canvas/objects # use the delete method here
        except:
            pass # leave this as pass, so it takes no action if there's an error
        f = Figure(figsize=(5,5), dpi=100)
        canvas = FigureCanvasTkAgg(f, master=courbe)
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2020-08-21
      相关资源
      最近更新 更多