-1

I would like to generate my python GUI at runtime Imagine the list being some data coming from a database, and I want buttons for every db line. How do I make this work?

import tkinter as tk

root = tk.Tk()

root.geometry("800x480")

def cmdLastafel(button):
    button["text"] = "deze"


lst= ["A","B","C"]
cnt = 0
for i in lst:
    cnt +=1
    btn = tk.Button(root)
    btn["text"] = i
    btn.configure(command=lambda: cmdLastafel(btn))
    btn.grid(row=cnt,column=0)

root.mainloop()

This gives me 3 buttons but when I press A, C text is changed.. I have a .net background, and there I would solve it by creating a new button at beginning of for loop, and storing the button in a list at the end of the loop. But I don't knwo how to force a new in python, or how to create an empty list of buttons..

1 Answers1

0

You can create buttons in a list.

Here's an example:

import tkinter as tk

root = tk.Tk()
root.geometry("800x480")

def cmdLastafel(button):
    button.config(text = "deze")

lst= ["A","B","C"]
buttons = []
for cnt, i in enumerate(lst):
    buttons.append(tk.Button(root,
                   text = i))
    # buttons[-1] refers to the last item in the list, so the button we just appended.
    # lambda btn=buttons[-1], stores the last button at the time of iteration to btn.
    buttons[-1].config(command=lambda btn=buttons[-1]: cmdLastafel(btn))
    buttons[-1].grid(row=cnt,column=0)

root.mainloop()

enter image description here

tgikal
  • 1,667
  • 1
  • 13
  • 27