【问题标题】:how to call a function of class based tkinter Frame from another class based frame [duplicate]如何从另一个基于类的框架中调用基于类的tkinter Frame的函数[重复]
【发布时间】:2021-11-16 03:37:33
【问题描述】:

我有一个 Tkinter 应用程序,它有多个基于类的框架,我想从另一个框架/类调用 ​​tkinter 框架中的一个函数。

例如,我的框架是这样的:


    
class_B(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
            
        def Update_class_b():
        label = tk.Label(class_B, text=f"Welcome", font=LARGEFONT)
        label.grid(row=1, column=0)

        # wigdgets
        button = tk.Button(self, text="START_TRIP", command=lambda: controller.show_frame(D_file.D_class)
        #i am using this controller to navigate between those pages

        # packing/grid
        button.grid(row=2, column=0, padx=10, pady=10)

现在,我想从另一个类基框架调用函数update_class_b。我现在怎么能做到这一点,我在标签小部件中传递class_B,同时使其如您所见并直接在class_A 中调用它,但它不起作用。请如果有人可以帮助我解决这个问题。 另外,我想从另一个基于类的框架中调用这个update_class_b 函数,比如按下Class_A 中的按钮时,这个函数应该是触发器

A 类会是这样的

class class_A(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        def do_something_in_class_B():
            #this should trigger Update_class_b function in class_B

        button = tk.Button(self, text="DO SOMETHING IN CLASS B", command=do_something_in_class_B).pack()

控制器类

class tkinterApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        self.frames = {}
        self.attributes('-fullscreen', True)
        


        for F in (file_A.Class_A,file_B.class_B):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(startPage.StartPage)


    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()


if __name__ == "__main__":
    app = tkinterApp()
    app.mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    假设您将帧存储在控制器框架中的字典中:

    func = controller.frames[class_B].update_class_b
    button = tk.Button(self, text="START_TRIP", command=func)
    button.grid(row=2, column=0, padx=10, pady=10)
    

    我们必须查看 MCVE 才能给出具体答案。

    【讨论】:

    • 我添加了控制器类,请看一下
    • 我明白我的假设是正确的。如果没有minimal reproducible example,我只能告诉你很多。
    • 我必须把这段代码放在哪里?我无法理解
    • 您没有向我们展示足够多的代码,让我们知道您需要将它放在哪里。询问软件问题时需要显示minimal reproducible example
    • 请看一下,我已经编辑了我希望在 A 类发生的问题
    猜你喜欢
    • 1970-01-01
    • 2013-02-04
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多