Can't find soulution tkinter KeyError: 0

Question:

from tkinter import *
from tkinter import font
window = Tk ()
window.title(" ")
button = {}
name = -1
def click(number):
    button[number].config(bg="gray")
    print(number)
for x in range(15):
    for y in range(15):
        name = name + 1
        button[name] = Button(window, command=click(name), bg="white")
        button[name].config(height=2, width=4)
        button[name].grid(column = x, row = y)

window.mainloop()

I get error line 13, in module and line 8, in click. Not sure why this is happening, before I added the command=click(name) to Button it worked, but after I added it it stopped working

Asked By: Sebastian Bardoff

||

Answers:

Adding in command=click(name) doesn’t work as you are trying to assign command to the value returned from click(name) (you are accidentally running the function, which is then causing the KeyError).

Instead, try doing command=lambda: click(name)

Answered By: Elijah Nicol
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.