" AttributeError:class Frame没有属性' show_frame'"

时间:2016-03-29 04:25:31

标签: python-2.7 tkinter

这是我的代码,我试图链接两个页面

from Tkinter import *

class Example(Frame):

    def __init__( self , parent, controller ):
        Frame.__init__(self, parent)       
        self.controller=controller 
        self.parent = parent
        self.parent.title("f2")
        self.parent.configure(background="royalblue4")
        self.pack(fill=BOTH, expand=1)

        w = 800
        h = 500

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - w)/2
        y = (sh - h)/2 
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

        self.logbtn1 = Button(self,text="SIGN UP",font=("Copperplate Gothic Bold",16),bg=("dark green"),activebackground=("green"),command=lambda: controller.show_frame("D:\java prgms\minor\signup"))
        self.logbtn1.place(x=325,y=175)

        self.logbtn2 = Button(self, text="LOGIN",font=("Copperplate Gothic Bold",16),bg=("cyan"),activebackground=("yellow"),command=lambda: controller.show_frame("D:\java prgms\minor\log1"))
        self.logbtn2.place(x=335,y=220)

        self.pack()

def main():      
    root = Tk()
    ex = Example(root,Frame)
    root.mainloop()  


if __name__ == '__main__':
    main() 

但是我收到此错误消息:

AttributeError: class Frame has no attribute 'show_frame'
how to remove this error 

1 个答案:

答案 0 :(得分:1)

首先,你不能像在command=lambda: controller.show_frame(...)中那样调用lambda。

假设您执行了我在当前程序中没有看到的必要导入,只需将这两个语句(在代码的两行中)替换为:command=controller.show_frame(...)

请阅读how to use lambda

其次,您的代码在此行周围包含其他错误:

if name == 'main':
   main()

将其更改为:

if __name__ == '__main__': 
   main() 

修正错误后,我成功运行了程序:

enter image description here

P.S。可能你会对这篇文章感兴趣:What does if __name__ == "__main__": do?