Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.2k views
in Technique[技术] by (71.8m points)

python - Deleting a figure generated by canvas in tkinter

I'm new here and that's my first question.

I want to build a program where the user inserts parameters for function through a scroll bar and generates a graph of that function in tkinter.

Here is my code

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

I already tried the .destroy () function as well as defining a function that hides the frame with .pack_forget () but nothing works


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would handle this on the matplotlib side. Always use the same canvas, so nothing changes on the Tkinter side. You can remove subplots from a Figure with 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...