代码之家  ›  专栏  ›  技术社区  ›  Evo

当mathplotlib集成在tkinter内部时,程序不可关闭

  •  0
  • Evo  · 技术社区  · 2 年前

    我将matplotlib与tkinter一起使用,我希望图形屏幕/画布/绘图位于tkinter窗口内,所以我制作了 将matplotlib窗口转换为tkinter内部的一个小部件 :

    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import tkinter as tk
    
    window = tk.Tk()
    fig, ax = plt.subplots()
    
    frame = tk.Frame(window)
    frame.pack()
    label = tk.Label(window,text="test")
    label.pack()
    
    canvas = FigureCanvasTkAgg(fig, master=frame)
    canvas.get_tk_widget().pack()
    def draw():
        ax.hist([1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5],5)
        canvas.draw()
    canvas.get_tk_widget().destroy()
    
    
    window.mainloop()
    

    但现在,当窗口关闭时,python终端继续运行,如果没有打开控制台选项卡,就无法关闭。 我在网上看过这个问题,据说我必须在最后重复plt.show()两次才能关闭matplotlib 但是 因为我没有使用plt.show()方法来显示图形 ,无法关闭。请帮我解决这个问题

    1 回复  |  直到 2 年前
        1
  •  0
  •   Vimlesh Bhatt    2 年前

    正如你所说, plt.show() 在这种情况下不起作用,因为您正在将Matplotlib绘图嵌入到Tkinter窗口中。为了正确地处理关闭窗口的问题,可以使用Tkinter窗口的destroy()方法在关闭窗口时正确地进行清理。这是修改后的代码:

    import tkinter as tk
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTk, NavigationToolbar2Tk
    
    def draw():
        ax.hist([1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5], 5)
        canvas.draw()
    
    def on_closing():
        window.destroy()
        plt.close()  # Close the Matplotlib plot
    
    window = tk.Tk()
    window.protocol("WM_DELETE_WINDOW", on_closing)  # Handle window closing event
    
    fig = Figure()
    ax = fig.add_subplot(111)
    
    canvas = FigureCanvasTk(fig, master=window)
    canvas_widget = canvas.get_tk_widget()
    canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
    
    toolbar = NavigationToolbar2Tk(canvas, window)
    toolbar.update()
    canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
    
    draw_button = tk.Button(window, text="Draw", command=draw)
    draw_button.pack()
    
    window.mainloop()