aidakemind
aidakemind

Reputation: 33

Change colour of tkinter button created in a loop?

I have created a grid of buttons using the code below:

for x in range(10):
    for y in range(10):
        btn = Button(frame, command=button_click(x, y))
        btn.config(height=1, width=1)
        btn.grid(column=x, row=y, sticky='nsew')

and I want to write the function button_click to turn the button a different colour once it has been clicked but as I have created all the buttons in a loop I don't have a specific variable name for each button so I'm not sure how best to do it? I didn't want to write 100 lines of code just creating buttons.. I thought maybe I could do this by passing the coordinates of the button to the function and somehow using this info but I can't find a solution. Any suggestions on how to do this or an alternative approach I could take would be greatly appreciated!

Upvotes: 1

Views: 284

Answers (1)

JacksonPro
JacksonPro

Reputation: 3275

Try this:

import tkinter as tk
import random

def button_click(btn):
    color = random.choice(['red', 'blue', 'green'])
    btn.config(bg=color)
    print(btn)

window = tk.Tk()

for x in range(10):
    for y in range(10):
        btn = tk.Button(window)    
        btn.config(text=f'{x}{y}',height=1, width=1, command=lambda button=btn: button_click(button))
        btn.grid(column=x, row=y, sticky='nsew')

window.mainloop()

Update: buttons on frame

import tkinter as tk
import random

def button_click(btn):
    color = random.choice(['red', 'blue', 'green'])
    btn.config(bg=color)
    print(btn)

window = tk.Tk()

frame = tk.Frame(window)
frame.pack()

for x in range(10):
    for y in range(10):
        btn = tk.Button(frame)    
        btn.config(text=f'{x}{y}',height=1, width=1, command=lambda button=btn: button_click(button))
        btn.grid(column=x, row=y, sticky='nsew')

window.mainloop()

Upvotes: 2

Related Questions