简体   繁体   中英

Python tkinter: changing color for a recently clicked button

I'm trying to have a program which would have a grid of 8x8 buttons which would on-click change their color My code looks like this:

def Function(self):
    for i in range(8):
        for j in range(8):
            a=Button(self,width=2,height=1,command=lambda widget="button"+str(i)+str(j):Click1(self,widget))
            a.grid(row=i,column=j)

def Click1(self):
    a["bg"]="blue"

The problem I have with this is that I keep getting an error saying:

NameError: name 'Click1' is not defined

any solutions for this?

You are not saving references to the Buttons, so you can't change them later on. What you should do is save references to the Buttons, for example in a list of lists (like a grid), so you can access them with the row and column number.

Here's a working example:

from Tkinter import *

class App():
    def __init__(self, root):
        self.root = root

    def Function(self):
        self.grid = []
        for i in range(8):
            row = []
            for j in range(8):
                row.append(Button(self.root,width=2,height=1,command=lambda i=i, j=j: self.Click1(i, j)))
                row[-1].grid(row=i,column=j)
            self.grid.append(row)

    def Click1(self, i, j):
        self.grid[i][j]["bg"]="blue"

root = Tk()
app = App(root)
app.Function()
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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