Tkinter 从另一帧中的不同 tk.Button 更新 matplotlib 图

Tkinter updating matplotlib figure from different tk.Button in another frame

我是第一次使用 Tkinter 构建 GUI,运行 在使用不同框架中的按钮更新 Matplotlib 图形中的数据时遇到了问题。下面是一些通用代码,用于显示我遇到的错误。

from Tkinter import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class testApp():
    def app(self):
        self.root = Tk()
        self.create_frame1()
        self.create_frame2()
        self.root.mainloop()

    def create_frame1(self):
        frame1 = Frame(self.root)
        frame1.grid(row=0)
        (x, y) = self.create_data()
        f = plt.Figure(figsize = (5,2), dpi=100)
        a = f.add_subplot(111)
        lines1, = a.plot(x, y)
        f.tight_layout()
        canvas = FigureCanvasTkAgg(f, frame1)
        canvas.get_tk_widget().grid()

    def create_frame2(self):
        frame2 = Frame(self.root)
        frame2.grid(row=1)
        reEval = Button(frame2, text = "Reevaluate", command = lambda: self.reRand()).grid(sticky = "W")

    def reRand(self):
        (x, y) = self.create_data()
        ax = self.root.frame1.lines1
        ax.set_data(x, y)
        ax.set_xlim(x.min(), x.max())
        ax.set_ylim(y.min(), y.max())
        self.root.frame1.canvas.draw()

    def create_data(self):  
        y = np.random.uniform(1,10,[25])
        x = np.arange(0,25,1)
        return (x, y)


if __name__ == "__main__":
    test = testApp()
    test.app()

当我运行这段代码时,我得到一个错误:

AttributeError: frame1

我认为我的问题源于我如何引用包含图形本身的框架,所以我相当确定这个问题是由于我缺乏 Tkinter 经验引起的。任何帮助将不胜感激。

这更多是因为使用 Python 类 而不是 Tkinter。您真正需要做的就是将 create_frame1 中的所有 frame1 更改为 self.frame1。同样在 reRand 中,self.root.frame1 变为 self.frame1.

因为名字 "frame1" 不存在于 create_frame1 的末尾之外,但是如果将其保存为 self 的属性,您以后可以访问它。