I'm fairly new to Python and completely new to posting on this forum (I've been using it for years, but have usually have more luck finding the answer by searching past questions. I'm stumped today though).
rows = 8
columns = 8
def onClick(args):
print("args: ", args)
myButtons = []
myButtons = [ ttk.Button(mainframe, text=str(i) + str(j), command=lambda:onClick([int(i),int(j)])) for i in range(columns) for j in range(rows) ]
for i in range(columns) :
for j in range(rows):
myButtons[i*rows+j].grid(column=i, row=j)
(I haven't included all the grid creation code but it's working fine, the buttons are displaying.).
I'm trying to call a click event for buttons in a grid. I tried to create the buttons with different args passing into the onClick event so that I know which button was clicked. I'm sure this worked when I created the buttons individually, rather than when I created them with list comprehension. Now though, no matter which button I click I get:
args: [7,7]
Can anyone point out where I'm going wrong please?
Thank you!
You need to use default values of arguments in lambda
:
myButtons = [ttk.Button(mainframe, text=str(i)+str(j), command=lambda i=i,j=j: onClick([i,j])) for i in range(columns) for j in range(rows)]
Also you can combine the list comprehension and the for loop together:
myButtons = []
for i in range(columns):
for j in range(rows):
btn = ttk.Button(mainframe, text=str(i)+str(j),
command=lambda i=i,j=j:onClick([i,j]))
btn.grid(column=i, row=j)
myButtons.append(btn)