Я пытаюсь сделать кнопки с циклом for запускает команду для изменения цвета этой кнопки.
Это работает, но изменяет только одну кнопку.
from tkinter import*
from tkinter.colorchooser import *
top=Tk()
buttonlist=[]
button_counter=0
def change_color():
#change button color
color=askcolor()
color=color[1]
buttonlist[0].configure(bg=color)
how_many_times=range(2)
y=25
for num in how_many_times:
buttonlist.append(Button(width=5,
relief=SUNKEN, bg="Black",
command=change_color))
buttonlist[button_counter].place(x=10, y=y)
y=y+100
button_counter=button_counter+1
top.mainloop()
Это не работает. С одной стороны, это заставляет меня изменить цвет перед созданием кнопки. Также выдает ошибку.
from tkinter import*
from tkinter.colorchooser import *
top=Tk()
buttonlist=[]
button_counter=0
def change_color(button_number):
#change button color
color=askcolor()
color=color[1]
buttonlist[button_number].configure(bg=color)
how_many_times=range(2)
y=25
for num in how_many_times:
buttonlist.append(Button(width=5,
relief=SUNKEN, bg="Black", command=change_color(button_counter)))
buttonlist[button_counter].place(x=10, y=y)
y=y+100
button_counter=button_counter+1
top.mainloop()
Ошибка:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py", line 19, in <module>
buttonlist.append(Button(width=5, relief=SUNKEN, bg="Black", command=change_color(button_counter)))
File "/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py", line 11, in change_color
buttonlist[button_number].configure(bg=color)
IndexError: list index out of range