Reputation: 121
I made 100 buttons and I want to change color of button which pushed. How can I do that? Here is my code.
import tkinter as tk
def settingships():
column = -1
row = 0
root = tk.Tk()
root.title('set ships')
root.geometry('470x310')
for i in range(101):
if i > 0:
if i%10 == 1:
row += 1
column = -1
column += 1
text=f'{i}'
btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
root.mainloop()
def collback(i):
def nothing():
btn.config(bg='#008000')
return nothing
Upvotes: 1
Views: 112
Reputation: 47183
First, i
is not used in collback()
. Second btn
is undefined in nothing()
. You should pass btn
to collback()
instead.
In order to do that you need to replace the following line:
btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
to:
btn = tk.Button(root, text=text)
btn.grid(column=column, row=row)
btn.config(command=collback(btn))
And modify collback()
as below:
def collback(btn):
def nothing():
btn.config(bg='#008000')
return nothing
Or simply use lambda to replace collback()
:
btn.config(command=lambda b=btn: b.config(bg='#008000'))
Upvotes: 2