'AxesSubplot' 对象在重新打开 Tkinter 后不可调用 window with plot

'AxesSubplot' object is not callable after reopen Tkinter window with plot

我创建了一个图表 class。它的 objects 的 y 值应该在稍后阶段更新。通过单击 Tkinter buttonplot 应显示在新的 window 中。到目前为止,当 button 被点击时,window 和 plot 被打开。但是一旦我用'plot'关闭window并尝试重新打开window,就会出现以下错误:

类型错误:'AxesSubplot' 对象不可调用

我使用以下代码:

import tkinter
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg)
from matplotlib.figure import Figure

root= tkinter.Tk()
root.geometry('800x800+50+50')
root.title('Spiel')

class Graph():
        
        def __init__(self, y):
            
            self.y = y
            
        def plot(self):
            self.window_graph = tkinter.Toplevel(root)
            self.window_graph.title("Graph")
            self.window_graph.geometry("300x300")
            
            self.fig = Figure(figsize=(5,5), dpi=55)
            self.plot = self.fig.add_subplot(111)
            self.plot.set_xlim([0,13])
            self.plot.set_ylim([0,400])
        
            #colors = ["red", "blue", "green", "yellow", "black"]
        
            self.line, = self.plot.plot(range(0,7),self.y,'r-', marker="o")
        
            self.plot.set_xlabel("Runde")
            self.plot.set_ylabel("Punkte")
            #self.plot.legend()
            self.canvas = FigureCanvasTkAgg(self.fig, master = self.window_graph)  
            self.canvas.draw()
            self.canvas.get_tk_widget().grid(row=0, column=0)
 
            
y = [1,2,3,4,5,6,7] 
graph_plot = Graph(y)

def plotting():
    graph_plot.plot()

tkinter.Button(root, text="Graph", command=plotting).pack()

root.mainloop()

有人对此有解决方案吗?

出现此问题是因为您正在设置 self.plot = self.fig.add_subplot(111)。在 Python 中,这会覆盖 class 的函数定义:

>>> def func():
...     pass
...
>>> func
<function func at 0x7f1f6d281f30>
>>> func = "abc"
>>> func
'abc'

只需重命名您的函数或变量即可。