2015-07-21 66 views
1

我一直在努力將一個變量傳遞給'simpledialog'框的一些代碼存在問題。但是,當我在__init__部分聲明變量時,該變量不能從該類中的任何其他方法訪問。使用'simpledialog'時聲明的變量未初始化

我已經創造了一種我試圖將字符串傳遞到框,以便創建「simpledialog」時,已填充的箱簡化工作示例。然後可以更改該值,並將新值輸出到控制檯。

from tkinter import * 
from tkinter.simpledialog import Dialog 


class App(Frame): 
    def __init__(self, parent): 
     Frame.__init__(self, parent) 
     self.parent = parent 

     Button(parent, text="Press Me", command=self.run).grid() 

    def run(self): 
     number = "one" 
     box = PopUpDialog(self, title="Example", number=number) 
     print(box.values) 

class PopUpDialog(Dialog): 
    def __init__(self, parent, title, number, *args, **kwargs): 
     Dialog.__init__(self, parent, title) 
     self.number = number 

    def body(self, master): 
     Label(master, text="My Label: ").grid(row=0) 
     self.e1 = Entry(master) 
     self.e1.insert(0, self.number) # <- This is the problem line 
     self.e1.grid(row=0, column=1) 

    def apply(self): 
     self.values = (self.e1.get()) 
     return self.values 

if __name__ == '__main__': 
    root = Tk() 
    app = App(root) 
    root.mainloop() 

當代碼運行,並且「按我」按鈕被按下時,我收到以下錯誤信息:

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ 
    return self.func(*args) 
    File "C:/Python/scratch.py", line 14, in run 
    box = PopUpDialog(self, title="Example", number=number) 
    File "C:/Python/scratch.py", line 20, in __init__ 
    Dialog.__init__(self, parent, title) 
    File "C:\Python34\lib\tkinter\simpledialog.py", line 148, in __init__ 
    self.initial_focus = self.body(body) 
    File "C:/Python/scratch.py", line 26, in body 
    self.e1.insert(0, self.number) 
AttributeError: 'PopUpDialog' object has no attribute 'number' 

如果我註釋掉self.e1.insert(0, self.number),代碼將工作,否則。

似乎很少有關於'simpledialog'的文檔,我一直在使用effbot.org上的示例來嘗試和了解更多關於對話框的知識。請注意,如果在PopUpDialog類的__init__方法中插入print(number)行,該編號將打印到控制檯。另外,如果我在正文()方法中初始化self.number變量(例如,self.number = "example"),則代碼將按預期工作。

我敢肯定,我在這裏錯過了一些愚蠢的東西,但如果你能提供任何關於可能發生什麼的建議,那將是非常感謝。

回答

2

問題出在您的PopUpDialog類中,在函數__init__處,您調用線路Dialog.__init__(self, parent, title),該行調用正文方法。問題是你在下一行初始化了self.number,這就是爲什麼self.number還沒有在body方法初始化。

如果您切換線它會爲你工作,就像這樣:

class PopUpDialog(Dialog): 
    def __init__(self, parent, title, number, *args, **kwargs): 
     self.number = number 
     Dialog.__init__(self, parent, title) 

編輯:

正如你可以在對話框的__init__方法見有上述行:

self.initial_focus = self.body(body)調用你的身體方法。

+0

非常好!很簡單!非常感謝您的幫助! – skyhammer

+0

不客氣。 –