在Python类之间传递数组

时间:2017-02-07 18:57:06

标签: python arrays lambda

我想在两个Python类之间传递xy数组中的数据。单击button后,我会运行command=lambda: controller.show_frame(PlotPage)以从SelectPage(选择数据)切换到PlotPage(绘制x和y)。我希望在页面切换之前或x lambda中保存ybutton。将数组保存为全局变量是将数据传递给PlotPage的最佳方法,还是有更方便的方法将这些数组包含在按钮lambda函数中?

# possible global variables
global x = [stuff x]
global y = [stuff y]    

class SelectPage(tk.Frame):
    def __init__(self,parent,controller):
        button = tk.Button(self,text="Plot",
            command=lambda: controller.show_frame(PlotPage),
            [some_lambda_here])    # Possible lambda addition

class PlotPage(tk.Frame):
    def __init__(self,parent,controller):
        [Tkinter plot intialization stuff]
        plotData(x,y)  # plotData creates the plot

控制器类:

class Project:

def __init__(self, *args,**kwargs):
    tk.Tk.__init__(self,*args,**kwargs)
    container = tk.Frame(self)

    container.pack(side="top",fill="both",expand=True)

    container.grid_rowconfigure(0,weight=1)
    container.grid_columnconfigure(0,weight=1)

    self.frames = {}

    for F in (SelectPage, PlotPage):

        frame = F(container, self)

        self.frames[F] = frame

        frame.grid(row=0,column = 0, sticky = "nsew")

    self.show_frame(StartPage)

def show_frame(self, container):

    frame = self.frames[container]
    frame.tkraise()

1 个答案:

答案 0 :(得分:1)

对于组件之间的通信,您应该看一下Observer设计模式和MVC架构。然后你可以沿着这些行构建程序(我在这里跳过Tk指令):

class Observable:
    def __init__(self, signals):
        # create signal map
    def connect(self, signal, handler):
        # append handler to the signal in the map
    def emit(self, signal, *args, **kwargs):
        # iterate over signal handlers for given signal

class Model(Observable):
    def __init__(self):
        super().__init__("changed")
        self.x = []
        self.y = []

    def set_x(self, x):
        self.x = x
        self.emit("changed")

    def append_x(self, value):
        self.x.append(value)
        self.emit("changed")

    # same for y

class PlotView(SomeTKTClass):
    def __init__(self, model):
        self.model = model
        model.connect("changed", lambda: self.plot(model.x, model.y))

     def plot(self, x, y):
        #some tk rendering here

# SelectPage and StartPage are defined somewhere.

class MainController(SomeTkClass):
    def __init__(self):
        # ...
        self.model = Model() 
        self.startPage = StartPage() # I suppose
        self.plotView = PlotView(self.model)
        self.selectPage = SelectPage()
        self.frames = {}

        for view in {self.startPage, self.plotView, self.selectPage}:
            self.frames[view.__class__] = view
            # ...
        self.show_frame(StartPage)

    def show_frame(self, container):
        frame = self.frames[container]
        # ...

Observer模式的实现可以通过多种方式完成。这里建议的很简单。有很多方法可以改进这个草图,但是想法是让可观察模型通知视图它的数据已经改变并且可以在图中重新绘制。