Python tkinter button question.

Asked 2 years ago, Updated 2 years ago, 109 views

class WidgetsDemo:
    def __init__(self):
        window=Tk()
        window.title ("Widget Demo")
        self.button = [[0 for col in range(5)] for row in range(8)]
        for self.i in range(0,8):
            for self.j in range(0,5):
                self.button[self.i][self.j]=Button(window,bg="white",command=self.colorbox)
                self.button[self.i][self.j].grid(row = self.i, column = self.j, sticky = W)

    def colorbox(self):
        self.button[self.i][self.j].configure(bg="red")
        print(self.i,self.j)j)

WidgetsDemo()

I can't make it change color when each button is pressed. What should I do? I don't know if I should just make several variables and make them react when pressed.

python tkinter button

2022-09-22 19:55

1 Answers

When you hand over the index to pressed, self.x, self.Don't turn it over with y, but use Lambda.

from tkinter import *


class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.buttons = []
        self.pack()
        self.CreateWidgets()

    def CreateWidgets(self):
        for i in range(0, 2):
            btns = []
            for j in range(0, 2):
                btns.append(Button(self, text="0", bg="white", command= lambda indexI=i, indexJ=j: self.pressed(indexI,indexJ)))
                btns[j].grid(row=i, column=j, sticky=W)
                btns[j].pack()
            self.buttons.append(btns)

    def pressed(self, indexI, indexJ):
        try:
            self.buttons[indexI][indexJ].configure(bg="black")
            print(indexI, indexJ)
        except:
            pass

root = Tk()
app = Application(master=None)
app.mainloop()


2022-09-22 19:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.