0

I'm making a randomized bingo card, but I'm absolutely stuck on this one problem. I want to make a button that changes colour when clicked, but I can't seem to make it target itself. When I use the code below, and click on a button, it will only change the button in the bottom right corner (which is the last one generated)

def colourChange():
    bingoButton.configure(bg="blue")

while whatever < 25:
    whatever += 1
    bingoButton = tk.Button(window,
                              text=whatever,
                              foreground="white",
                              background="black",
                              font=myFont,
                              command=colourChange
                              )
    bingoButton.config(height=3, width=5)
    bingoButton.grid(column=gridPosX,row=gridPosY)
    gridPosX += 1
    if gridPosX == 5:
        gridPosX = 0
        gridPosY += 1

A lot of the variables and stuff are just placeholders, since this is just a test program to get my bearings straight before moving it to the main project.

Kolabold
  • 3
  • 2
  • 1
    Does this answer your question? [tkinter creating buttons in for loop passing command arguments](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments) – jasonharper Nov 11 '21 at 23:23
  • It might, but I just can't quite wrap my head around what exactly I need to do. – Kolabold Nov 11 '21 at 23:41

1 Answers1

0

You could bind the click event of the buttons to a callback function, e.g. colourChange, as you create them.

bingoButton.bind('<Button-1>', colourChange)

The callback function would need to change to something like this.

def colourChange(event):
   # event.widget refers to the widget, e.g. button, that
   # has triggered the event
   event.widget['bg'] = 'blue'
norie
  • 9,609
  • 2
  • 11
  • 18
  • Took a bit for me to understand since I'm rather new to coding, but in the end, it solved my problem perfectly. Thank you. – Kolabold Nov 12 '21 at 00:08