AttributeError:类型对象“类”没有属性“方法”

时间:2019-02-22 19:15:15

标签: python python-3.x tkinter

继续获取错误AttributeError: type object 'SampleApp' has no attribute 'draw'。我查看了有关此问题的其他资源,但没有看到试图从另一个类调用该方法的地方。我还尝试了def draw()内外的_init_。 这样做的目的是在类B上为用户输入,并且在单击按钮时将小部件绘制到Sample App的框架上,但到目前为止我还不能这样做。

import tkinter as tk

class SampleApp(tk.Tk):


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

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


        self.left_frame = tk.Frame(self, width=426, height=600)
        self.left_frame.grid(column=0, row=3, columnspan=3, rowspan=10)

        self.right_frame = tk.Frame(self, width=855, borderwidth=2, 
        relief="solid")
        self.right_frame.grid(column=4, row=0, rowspan=9, sticky="nsew")


        self.frames = {}
        for F in (A, B):
            page_name = F.__name__
            frame = F(parent=self.left_frame, controller=self)
            frame.configure(width=426, height=511, borderwidth=2, 
            relief="solid")
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, columnspan=3, 
            rowspan=2,sticky="nsew")

        self.show_frame("A")


        def draw():
            print("We")
            label = tk.Label(self.left_frame_bottom, text="Hello")
            label.pack()


class A(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        button = tk.Button(self, text="Go to the start page",
                       command=lambda: controller.show_frame("B"))
        button.pack()

 class B(tk.Frame):

     def __init__(self, parent, controller):
         tk.Frame.__init__(self, parent)
         self.controller = controller


         submit_button = tk.Button(self, text="Submit", 
         command=lambda:SampleApp.draw())
         submit_button.place(x=180, y=320)


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

2 个答案:

答案 0 :(得分:0)

首先,您需要修复draw的缩进-缩进太多了。 def draw的缩进必须与def show_frame相同。

第二,由于draw是控制器上的方法,因此您需要通过控制器实例来调用它:

self.controller.draw()

答案 1 :(得分:-1)

扩展您的draw()函数,使其与__init__()处于同一级别。确保传递了自我def draw(self):,如果在创建实例时需要运行它,则只需在self.draw()定义中调用__init__()