简体   繁体   English

我如何 get.configure 在 for 循环中工作

[英]How do i get .configure to work in a for loop

I'm trying to write some code which allows me to press a button, then the background of that button will change.我正在尝试编写一些允许我按下按钮的代码,然后该按钮的背景会改变。 the code I've written only changes the colour of the final button when any of the other buttons are pressed.我编写的代码仅在按下任何其他按钮时更改最终按钮的颜色。 can someone help me resolve this?有人可以帮我解决这个问题吗?

import tkinter as tk

column = 0
                   
def click_me():
    button.configure(bg='red')

for i in range(10):
    button = tk.Button(text="___", font='Fixedsys 20 bold', command=click_me)
    button.grid(column=column, row=0)
    column += 1

Try this:尝试这个:

import tkinter as tk
from functools import partial


column = 0

def click_me(button):
    button.configure(bg="red")

for i in range(10):
    button = tk.Button(text="Button %i" % i, font="Fixedsys 20 bold")
    # Create the command
    command = partial(click_me, button)
    button.config(command=command)
    button.grid(column=column, row=0)
    column += 1

I passed in the button as a parameter to the function.我将按钮作为参数传递给 function。 For more info on how to use partial read this .有关如何使用partial的更多信息,请阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM