Home > other >  Making Button Change Own Colour in Tkinter
Making Button Change Own Colour in Tkinter

Time:11-12

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.

CodePudding user response:

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'
  • Related