Barty 200YT
Barty 200YT

Reputation: 44

I am trying to create buttons in bulk but the command function doesn't want to work

I want to create tkinter buttons in bulk by using a for loop and the exec function but when i set the command it keeps on calling the function for the last piece in my database

for i in FirstFloor:
    exec('room_%d = CreateRoom(FirstFloor[i]["name"])'%index)
    exec('lbl_%d = Button(window, text=FirstFloor[i]["name"], command=lambda: move(FirstFloor[i]["x"], FirstFloor[i]["y"]), bg="light grey")'%index)
    exec('lbl_%d.grid(column=FirstFloor[i]["x"], row=FirstFloor[i]["y"], columnspan=FirstFloor[i]["xspan"], rowspan=FirstFloor[i]["yspan"])'%index)
    if FirstFloor[i]["locked"] == True:
        exec('lbl_%d.config(state="disabled", bg="red")'%index)
    index += 1

When i run this piece of code and click a button no matter which button i press it keeps going to same object

Upvotes: 0

Views: 76

Answers (2)

Mike - SMT
Mike - SMT

Reputation: 15226

You can create buttons in bulk without exec. You can use a list, dict or tuple. I typically use a list.

By using a list we can reference the index to interact with the button.

Example:

import tkinter as tk

root = tk.Tk()
button_list = []


def do_something(some_value):
    print(button_list[some_value]['text'])


for i in range(10):
    button_list.append(tk.Button(root, text='Button {}'.format(i+1), command=lambda i=i: do_something(i)))
    button_list[-1].grid(row=i, column=0)

root.mainloop()

Upvotes: 1

Paul M.
Paul M.

Reputation: 10799

Change this:

command=lambda: move(FirstFloor[i]["x"]

to this:

command=lambda i=i: move(FirstFloor[i]["x"]

Upvotes: 1

Related Questions