简体   繁体   中英

Making Button Change Own Colour in Tkinter

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.

You could bind the click event of the buttons to a callback function, eg 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM