2016-01-26 69 views
0

我想從列表中生成一堆變量,這將從另一個函數調用。使用Python中的循環創建列表中的變量名稱

如果我單獨創建它們(如在代碼的註釋部分中),一切工作正常(通過罰款,我的意思是,我可以使用下面列出的get_data函數訪問日期)。但是,當我使用的循環中,GET_DATA是給錯誤:

File "main.py", line 97, in get_data 
    dAu = self.Author.get_text() 
AttributeError: 'MyWindow' object has no attribute 'Author' 

所以,很明顯,在循環中,編輯我期待,現場[0],

self.field = self.field[0]=self.Author 

但事實並非如此。 編輯COMPLETE

self.field != self.Author 

爲我所願。 我怎樣才能得到它?

有問題的代碼是:

# Generate the Entry fields 
    self.notebook = Gtk.Notebook() 
    # self.LAuthor = Gtk.Label("Author") 
    # self.EAuthor = Gtk.Entry() 
    # self.page = Gtk.Grid() 
    # self.page.attach(self.LAuthor, 0, 0, 2, 1) 
    # self.page.attach_next_to(self.EAuthor, self.LAuthor, Gtk.PositionType.RIGHT, 1, 1) 
    # self.notebook.append_page(self.page, Gtk.Label("Trial")) 

    xpos = 0 
    minf = 0 
    fields = ["Author", "Year", "Journal", "Title", "Publisher", "Page", 
       "Address", "Annote", " Booktitle", "Chapter", "Crossred", 
       "Edition", "Editor", "HowPublished", "Institution", "Month", 
       "Note", "Number", "Organization", "Pages", "Publishers", 
       "School", "Series", "Type"] 
    Tabs = ["Essential", "Publishers", "Extra I", "Extra II"] 
    for note in range(int(len(fields)/6)): 
     ypos = 0 
     self.npage = "page"+str(note) 
     self.npage = Gtk.Grid() 
     self.npage.set_border_width(10) 
     maxf = minf+6 
     for field in fields[minf:maxf]: 
      print(field) 
      self.lfield = "L" + field 
      self.lfield = Gtk.Label(field) 
      self.field = Gtk.Entry() 
      self.field.set_placeholder_text(field) 
      self.npage.attach(self.lfield, xpos, ypos, 2, 1) 
      self.npage.attach_next_to(self.field, self.lfield, 
             Gtk.PositionType.RIGHT, 1, 1) 
      ypos += 1 

     self.notebook.append_page(self.npage, Gtk.Label(Tabs[note])) 
     minf = maxf 

而且get_data功能就是:

def get_data(self, widget): 
    dAu = self.Author.get_text() 
    print(dAu) 

請幫助。

回答

2

使用字典 - 例如:

self.all_fields = dict() 

field = "Author" 
self.all_fields[field] = ... 
# self.all_fields["Author"] = ... 

,然後你可以使用

def get_data(self, widget): 
    dAu = self.all_fields["Author"].get_text() 
    print(dAu) 
相關問題