2013-10-19 41 views
1

我想創建一個對話框,將從彈出對話框中獲得一個社會安全號碼(或simular輸入),但是當我嘗試我得到一個錯誤說,類沒有該屬性。下面是代碼:訪問一個變量,從一個不同的類 - 自定義對話框

from Tkinter import * 

class App: 
    def __init__(self, master): 
     b = Button(text="Click for social dialog", command=self.getSocial) 
     b.grid(row=0, column=0) 
    def getSocial(self): 
     d = socialDialog(root) 
     print d.social 
class socialDialog: 
    def __init__(self, master): 
     self.top = Toplevel() 
     Label(self.top, text='Social Security #: ').grid(row=0, column=0) 
     self.entry = Entry(self.top) 
     self.entry.grid(row=0, column=1) 
     self.entry.focus_set() 
     self.top.bind('<Key>', self.formatData) 
     self.top.bind('<Return>', self.ok) 
    def formatData(self, master): 
     currentData = self.entry.get() 
     if len(currentData) == 3: 
      self.entry.insert(3, '-') 
     elif len(currentData) == 6: 
      self.entry.insert(6, '-') 
     elif len(currentData) > 11: 
      self.entry.delete(-1, END) 
    def ok(self, master): 
     self.social = self.entry.get() 
     self.top.destroy() 
root = Tk() 
app = App(root) 
root.mainloop() 
+0

我能這次來弄明白,但它是很容易幫助您一個錯誤,如果你打印錯誤堆棧跟蹤 - 這有它寶貴的調試信息! – Brionius

回答

0

問題是print在顯示對話框後立即執行,因爲對話框沒有以模態方式顯示。

爲了解決這個問題,嘗試這樣的事情:

d = socialDialog(root) 
root.wait_window(d.top) 
print d.social 

但要注意的是,如果不輸入任何操作關閉對話框仍然會出現錯誤。爲了防止這種情況,要確保social屬性都有一個默認值:

class socialDialog: 
    social = None 
0

的問題是你的socialDialog類你按一下回車鍵,它調用ok方法後,只分配一個social屬性。因此,當您調用getSocial(實例化socialDialog),然後立即訪問social屬性時,socialDialog實例中的social屬性尚不存在。

我不知道該代碼你的長期目標是什麼,但立即解決將是改變getSocial功能正是如此:

def getSocial(self): 
    d = socialDialog(root) 
    # print d.social 

再加入

print self.social 

ok方法。

相關問題