Tkinter 从不同的 tk 更新 matplotlib 图形.另一个框架中的按钮



我第一次使用 Tkinter 构建 GUI,但在使用不同帧中的按钮更新 Matplotlib Figure 中的数据时遇到了问题。 下面是一些通用代码,以显示我遇到的错误。

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

当我运行此代码时,出现错误:

属性错误:帧 1

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

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

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

最新更新