-1

I am working on a python app about houseplants and I'm using tkinter. I have a list of plants that all have a specific attribute (in this case, it's the type of plant "foliage") that is called from a database using sqlite. I want to use a for loop to create a button for each item in the list and have each button on a different row and have the text for each button be a different item. I want to use a for loop so as I add plants to the database (and therefor list), I won't have to change my code every time.

foliage_list = []
c.execute("SELECT name FROM plants WHERE type_of_plant = 'foliage'")
foliage_result = c.fetchall()
foliage_list.append(foliage_result)
foliage_num = len(foliage_list)

for item in foliage_list:
    for i in range(foliage_num):
        tk.Button(self, text=item)
        tk.Button[i].grid(row=i+1, column=0, padx=30, pady=30)

Here I have created the list and then attempted to use a for loop to create a button for each item in the list. I know this is wrong (it doesn't work) but I cannot figure out how to make it work. How can I do this?

Edit: I have changed my code to this:

for item in foliage_list:
    for i in range(foliage_num):
        tk.Button(self, text=item).grid(row=i+1, column=0, padx=30, pady=30)

I seems to now create a button for every item in the list in every row for how many rows there are items. I think this has something to do with using a nested for loop.

1 Answers1

-1

This is wrong:

tk.Button(self, text=item)
tk.Button[i].grid(row=i+1, column=0, padx=30, pady=30)

Use:

tk.Button(self, text=item).grid(row=i+1, column=0, padx=30, pady=30)
hussic
  • 1,816
  • 9
  • 10