更改在循环中创建的tkinter按钮的颜色? [英] Change colour of tkinter button created in a loop?

查看:60
本文介绍了更改在循环中创建的tkinter按钮的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码创建了一个按钮网格:

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

,我想编写一下button_click函数,以在单击按钮后将其更改为另一种颜色,但是由于我在循环中创建了所有按钮,因此每个按钮都没有特定的变量名,所以我不确定如何最好地做到这一点?我不想只创建按钮就编写100行代码..我想也许可以通过将按钮的坐标传递给函数并以某种方式使用此信息来做到这一点,但我找不到解决方案.任何有关如何执行此操作或我可以采用的替代方法的建议,将不胜感激!

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!

推荐答案

尝试一下:

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

更新:框架上的按钮

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

这篇关于更改在循环中创建的tkinter按钮的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆