2012-10-22 29 views
1

我下面這個介紹到Tkinter的,特別是頁面上的對話框填寫例29. http://www.ittc.ku.edu/~niehaus/classes/448-s04/448-standard/tkinter-intro.pdf麻煩與Tkinter的錄入組件

,我發現了以下錯誤:

d = MyDialog(root) 
TypeError: this constructor takes no arguments 

我刪除了參數從變量d和wait_window的參數(參見下面的代碼)並且程序將運行,但是沒有輸入字段。

下面是代碼

from Tkinter import * 

class MyDialog: 

    def init(self, parent): 

     top = Toplevel(parent) 

     Label(top, text="Value").pack() 

     self.e = Entry(top) 
     self.e.pack(padx=5) 

     b = Button(top, text="OK", command=self.ok) 
     b.pack(pady=5) 

    def ok(self): 
     print "value is", self.e.get() 

     self.top.destroy() 

root = Tk() 
Button(root, text="Hello!").pack() 
root.update() 

d = MyDialog(root) 

root.wait_window(d.top) 

回答

3

變化

def init(self, parent): 

def __init__(self, parent): 

object.__init__的文檔。

+2

嗯...... OP實際上並沒有使用'object .__ init__',因爲這是一箇舊式的類 - 但是你是對的,它的功能基本上是一樣的。 – mgilson

+0

@ user1104854 - 查看我在這個問題上的編輯 – mgilson

+1

如果您有新問題,請將其作爲新問題發佈。並且請不要編輯您的問題以包含答案。您的原始問題已得到解答。請接受其中一個答案。 – 2012-10-22 12:20:08

3

您需要更改

def init(self, parent): 
    ... 

def __init__(self, parent): 
    ... 

(注意包圍雙下劃線)。

在python中,文檔對構造函數有點模糊,但__init__通常被稱爲構造函數(儘管有些人會認爲這是__new__的工作)。除了語義學之外,傳遞給MyClass(arg1,arg2,...)的參數將傳遞給__init__(前提條件是您不會在__new__中做有趣的事情,這是討論不同的時間)。例如:

class MyFoo(object): #Inherit from object. It's a good idea 
    def __init__(self,foo,bar): 
     self.foo = foo 
     self.bar = bar 

my_instance = MyFoo("foo","bar") 

正如,因爲你沒有定義__init__,正在使用你的代碼的默認這相當於:

def __init__(self): pass 

它沒有參數(比強制self除外)


您還需要做到:

self.top = Toplevel(...) 

自從以後您嘗試獲得最高屬性(d.top),但d沒有屬性top,因爲您從未將其添加爲屬性。