简体   繁体   中英

create variable name from list using a loop in python

I am trying to generate a bunch of variables from a list, which will be called from another function.

If I create them separately(as in the commented part of the code), everything is working fine(by fine, I mean, I can access the date using get_data function listed below). But, when I am using the loop, the get_data is giving error:

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

So, it is obvious that inside the loop, EDIT I am expecting, for field[0],

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

but this is not the case. EDIT COMPLETE

self.field != self.Author

as I wished. How can I get that?

The code in question is:

    #  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

And the get_data function is just:

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

Kindly help.

Use dictionary - for example:

self.all_fields = dict()

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

and then you can use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM