2015-01-14 127 views
2

我查了一下,但找不到我錯誤的答案。下面是代碼:Tkinter AttributeError:對象沒有屬性'tk'

import tkinter as tk 

root=tk.Tk() 

class Page(tk.Frame): 
    '''Enables switching between pages of a window.''' 
    def __init__(self): 
     self.widgets={} 
     self.grid(column=0,row=0) 

page=Page() 

tk.mainloop() 

以下是錯誤:

Traceback (most recent call last): 
    File "C:\Documents and Settings\Desktop\Python Scripts\Tkinter.py", line 11, in <module> 
    page=Page() 
    File "C:\Documents and Settings\Desktop\Python Scripts\Tkinter.py", line , in __init__ 
    self.grid(column=0,row=0) 
    File "C:\Python34\lib\tkinter\__init__.py", line 2055, in grid_configure 
    self.tk.call( 
AttributeError: 'Page' object has no attribute 'tk' 

我是相當新的Tkinter的,而這個錯誤我難住了。我非常感謝任何幫助,謝謝!

回答

8

您的Page init方法應該調用Frame的init。

class Page(tk.Frame): 
    '''Enables switching between pages of a window.''' 
    def __init__(self): 
     super(Page, self).__init__() 
     self.widgets={} 
     self.grid(column=0,row=0) 
+0

非常感謝,但是一般使用'super'究竟是什麼? – PlatypusVenom

+1

@PlatypusVenom http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods – Scironic

+1

['super'](https://docs.python.org/3/library/functions.html #super)通常用於訪問屬於給定對象的父類的方法。在這裏,'super(Page,self)'返回一個Frame類似的'self'的代理,並且調用'__init __()'調用'Frame .__ init __()'。 – Kevin

相關問題