-3

I was creating a sort of button-based paint with tkinter, so I wanted to give every button a command to paint itself.

     for i in range(xc*yc):

             grid.append(Button(wn,text="    ",bg="white",padx=5,pady=5))

             grid[-1].config(command = paint(i))  <--????

             grid[-1].place(x= (i%xc) * 30 +60, y = (math.floor(i/xc) * 30)+30)

The problem is that every button recieves the command "paint(i)" with the final value of i, so everytime it paints the last button

xWourFo
  • 35
  • 4
  • Does this answer your question? [function-callback-in-event-binding-w-and-w-o-parentheses](https://stackoverflow.com/questions/54421018) – stovfl Jun 17 '20 at 09:45
  • 1
    Your code would not have the mentioned output because `paint(i)` will be executed when it is being assigned to `command` option. Your mentioned output will happen when `grid[-1].config(command=lambda: paint(i))` is used instead. To fix the issue, use `grid[-1].config(command=lambda i=i: paint(i))`. – acw1668 Jun 17 '20 at 09:59

2 Answers2

-2

Use root.update() method forecefully updates UI.so you can use that to see every iteration of for loop , if you call it inside that

Vignesh
  • 1,553
  • 1
  • 10
  • 25
-2

Maybe something like

for i in range(xc*yc):
    button = Button(wn,text="    ",bg="white",padx=5,pady=5)
    grid.append(button)
    button.config(command = paint(i, button)) # note the additional reference to button here!
    button.place(x= (i%xc) * 30 +60, y = (math.floor(i/xc) * 30)+30)

would be helpful.

glglgl
  • 89,107
  • 13
  • 149
  • 217