关闭带有图形和 canvas 的 tkinter 应用程序时出错

Error when closing tkinter app with figure and canvas

当我调整右侧的大小时展开 window 然后关闭它时出现以下错误: _tkinter.TclError: 无效命令名称“.!scrollbar” 可能与 canvas 小部件有关。 我尝试了很多,但没有结果。

谁能帮帮我?

代码如下

import tkinter as tk
from matplotlib.figure import Figure
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root=tk.Tk()

vscrollbar = tk.Scrollbar(root)

canvasF2= tk.Canvas(root,yscrollcommand=vscrollbar.set)

vscrollbar.config(command=canvasF2.yview)
vscrollbar.pack(side=tk.RIGHT, fill=tk.Y) 

frame2=tk.Frame(canvasF2) #Create the frame which will hold the widgets

canvasF2.pack(side="left", fill="both", expand=True)

##Updated the window creation
canvasF2.create_window(0,0,window=frame2, anchor='nw')
#
fig = Figure(figsize=(10, 4), dpi=100)
t = np.arange(0, 3, .01)
a = fig.add_subplot(111)
a.plot(t, 2 * np.sin(2 * np.pi * t))

canvas = FigureCanvasTkAgg(fig, frame2)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().grid(row=4, column=0, columnspan=2, sticky="nswe")

def on_configure(event):    
    canvasF2.configure(scrollregion=canvasF2.bbox('all'))

root.bind('<Configure>', on_configure) 

root.mainloop()

我不确定为什么在 window 关闭时会触发此错误,我的猜测是在关闭 window 之后,小部件 canvasF2 没有被正确销毁。因此,如果我们在关闭 window 之前正确销毁 canvasF2,则不会触发错误。我认为会有更好的方法来做到这一点,但这是我所做的。

我处理了 deletion of the window by using protocol method。我将其添加到您的代码末尾,并且在销毁主 window 之前销毁 canvasF2 没有出现任何错误。

def close_window():
    canvasF2.destroy()
    root.destroy()

root.protocol("WM_DELETE_WINDOW", close_window)

完整代码:

import tkinter as tk
from matplotlib.figure import Figure
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root=tk.Tk()

vscrollbar = tk.Scrollbar(root)

canvasF2= tk.Canvas(root,yscrollcommand=vscrollbar.set)

vscrollbar.config(command=canvasF2.yview)
vscrollbar.pack(side=tk.RIGHT, fill=tk.Y) 

frame2=tk.Frame(canvasF2) #Create the frame which will hold the widgets

canvasF2.pack(side="left", fill="both", expand=True)

##Updated the window creation
canvasF2.create_window(0,0,window=frame2, anchor='nw')
#
fig = Figure(figsize=(10, 4), dpi=100)
t = np.arange(0, 3, .01)
a = fig.add_subplot(111)
a.plot(t, 2 * np.sin(2 * np.pi * t))

canvas = FigureCanvasTkAgg(fig, frame2)  # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().grid(row=4, column=0, columnspan=2, sticky="nswe")

def on_configure(event):    
    canvasF2.configure(scrollregion=canvasF2.bbox('all'))

root.bind('<Configure>', on_configure) 


def close_window():
    canvasF2.destroy()
    root.destroy()

root.protocol("WM_DELETE_WINDOW", close_window)

root.mainloop()

希望对您有所帮助!