【问题标题】:Deleting a figure generated by canvas in tkinter在 tkinter 中删除画布生成的图形
【发布时间】:2023-03-09 06:47:01
【问题描述】:

我是新来的,这是我的第一个问题。

我想构建一个程序,用户通过滚动条插入函数参数,并在 tkinter 中生成该函数的图形。

这是我的代码

    from tkinter import*
    import tkinter
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
    from matplotlib.backend_bases import key_press_handler
    from matplotlib.figure import Figure
    import numpy as np
    
    root = Tk()
    root.title("Grath")
    #root.geometry('500x600')
    
    var_a = DoubleVar()
    var_b = DoubleVar()
    var_c = DoubleVar()
        
    x1 = np.linspace(100, 0, 1000)
    
    def y(x):
        a = float(var_a.get())
        b = float(var_b.get())
        c = float(var_c.get())
    return a*x**2+b*x+c

def graph():
    fig.add_subplot(111).plot(x1, y(x1))
    canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
    canvas.draw()
    canvas.get_tk_widget().pack()
 

#Labels and Bottons
label0=Label(root,text="Ploting f(x) = ax^2+b*x+c").pack()    
    
label1=Label(root,text="Val of a").pack()
textbox1=Scale(root,from_=0,to=10,orient=HORIZONTAL,variable = var_a).pack()

label2=Label(root,text="Val of b").pack()
textbox2=Scale(root,from_=0,to=10,orient=HORIZONTAL,variable = var_b).pack()

label3=Label(root,text="val of c").pack()
textbox3=Scale(root,from_=0,to=10,orient=HORIZONTAL,variable = var_c).pack()

button1 = Button(root,text="Run",command=graph).pack() 


fig = Figure(figsize=(5, 4), dpi=100)
canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack()
#canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

tkinter.mainloop()

我已经尝试过 .destroy () 函数以及定义一个用 .pack_forget () 隐藏框架的函数,但没有任何效果

【问题讨论】:

    标签: python matplotlib tkinter canvas


    【解决方案1】:

    我会在 matplotlib 端处理这个问题。始终使用相同的画布,因此 Tkinter 端没有任何变化。您可以使用 delaxes 从图中删除子图。

    def graph():
        # remove existing subplot
        if fig.axes:
            fig.delaxes(fig.axes[0])
        fig.add_subplot(111).plot(x1, y(x1))
        # update canvas
        canvas.draw()
        canvas.get_tk_widget().pack()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多