python tkinter button 질문입니다.

조회수 2355회
class WidgetsDemo:
    def __init__(self):
        window=Tk()
        window.title("위젯 데모")
        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)

WidgetsDemo()

도저히 각각의 버튼을 눌렸을떄 색 변화하게 만들고 싶어도 못하네요. 어떻게 해야될까요? 그냥 변수 여러개 만들어서 여러개 함수 만들어서 각각 눌렸을떄 반응하게 만들어야 될지..

1 답변

  • pressed에 index를 넘겨줄 때 self.x, self.y와 같이 넘기지 말고 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()
    
    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)