0

I'm trying to write some code which allows me to press a button, then the background of that button will change. the code I've written only changes the colour of the final button when any of the other buttons are pressed. can someone help me resolve this?

import tkinter as tk

column = 0
                   
def click_me():
    button.configure(bg='red')

for i in range(10):
    button = tk.Button(text="___", font='Fixedsys 20 bold', command=click_me)
    button.grid(column=column, row=0)
    column += 1
TheLizzard
  • 7,248
  • 2
  • 11
  • 31
  • 1
    You are only storing the last `button` that is created. Try using a list or look at [this](https://stackoverflow.com/q/10865116/11106801) – TheLizzard Mar 19 '21 at 18:59

1 Answers1

1

Try this:

import tkinter as tk
from functools import partial


column = 0

def click_me(button):
    button.configure(bg="red")

for i in range(10):
    button = tk.Button(text="Button %i" % i, font="Fixedsys 20 bold")
    # Create the command
    command = partial(click_me, button)
    button.config(command=command)
    button.grid(column=column, row=0)
    column += 1

I passed in the button as a parameter to the function. For more info on how to use partial read this.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31