2015-11-20 183 views
0

我正在開發一個GUI的一個項目,一旦我把所有這一切都爲一類,它返回說全局變量「的getInfo」未定義

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__ 
    return self.func(*args) 
    File "c:\users\ryan\documents\visual studio 2015\Projects\Group_3_Project\Group_3_Project\Group_3_Project.py", line 30, in <lambda> 
    b1 = Button(root, text = 'Submit', command = (lambda e = ents: getInfo(e))) 
NameError: global name 'getInfo' is not defined 

這裏是我到目前爲止的代碼:

from tkinter import* 


class GUI: 
    fields = 'Last Name', 'First Name', 'Field', 'Phone Number', 'Office number' 

    def getInfo(entries): 
     for entry in entries: 
      field = entry[0] 
      text = entry[1].get() 
      print('%s: "%s"' % (field, text)) 

    def makeForm(root, fields): 
     entries = [] 
     for field in fields: 
      row = Frame(root) 
      lab = Label(row, width = 15, text = field, anchor = 'w') 
      ent = Entry(row) 
      row.pack(side = TOP, fill = X, padx = 5, pady = 5) 
      lab.pack(side = LEFT) 
      ent.pack(side = RIGHT, expand = YES, fill = X) 
      entries.append((field, ent)) 
     return entries 

    if __name__ == '__main__': 
     root = Tk() 
     root.wm_title("HoursWizard") 
     ents = makeForm(root, fields) 
     root.bind('<Return>', (lambda event, e = ents: getInfo(e))) 
     b1 = Button(root, text = 'Submit', command = (lambda e = ents: getInfo(e))) 
     b2 = Button(root, text = 'Quit', command = root.quit) 
     b1.pack(side = LEFT, padx = 5, pady = 5) 
     b2.pack(side = LEFT, padx = 5, pady = 5) 
     root.mainloop() 

我不知道發生了什麼,爲什麼它不能正常工作。我相信這是一個簡單的解決方案,我只是錯過了一些東西。任何幫助表示讚賞。謝謝!

+1

你爲什麼要將這一切都包裝在'class GUI'中? – user2357112

+0

我有更多的代碼,我將要投入。這只是獲取用戶基本信息的GUI。 –

回答

1

您應該檢查official Python tutorial並查看關於課程的部分。基本上,您的範圍和命名空間不是您認爲的那樣。每個類方法(除非它被指定爲靜態)首先傳遞實例本身,通常用self表示。然後您會參考self.myattribute的實例屬性。例如,在getInfo中,您所稱的entries根本不是條目,而是已創建的GUI類的實例。

我強烈建議你查閱一些關於如何製作OO Tkinter應用程序的教程。它通常是這樣的:

class App: 
    def __init__(self, parent): 
     self.parent = parent 
     self.parent.after(5000, self.other_method) # just a demo 
     # create buttons, lay out geometry, etc. 
    def other_method(self): 
     self.do_print() 
    def do_print(self): 
     print('hello world') 

root = Tk() 
app = App(root) 
root.mainloop()