Change colour of tkinter button created in a loop?

匆匆过客 提交于 2021-01-28 11:20:44

问题


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!


回答1:


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()


来源:https://stackoverflow.com/questions/65325062/change-colour-of-tkinter-button-created-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!