2016-07-05 17 views
1

tkinterを使用して8 x 8のボタンマトリックスを作成しています。個々のボタンを押したときに最後のリストに追加されます(例:finalList =((0,0)、(5,7)、 6,6)、...)、私はすぐに8x8(x、y)座標の画像を作成することができます。ボタンを使ってウィンドウを作成しましたが、これらのボタンを関数で参照してボタンの色を変更、一覧表示、または色を変更することもできます。ボタンをクリックして解決策を見つけようとしています。tkinter複数のボタンの色の変更

from tkinter import * 

class App: 

    def updateChange(self): 
     ''' 
     -Have the button change colour when pressed 
     -add coordinate to final list 
     ''' 
     x , y = self.xY 
     self.buttons[x][y].configure(bg="#000000") 

    def __init__(self, master): 
     frame = Frame(master) 
     frame.pack() 

     self.buttons = [] # Do I need to create a dict of button's so I can reference the particular button I wish to update? 
     for matrixColumn in range(8): 
      for matrixRow in range(8): 
       self.xY = (matrixColumn,matrixRow) 
       stringXY = str(self.xY) 
       self.button = Button(frame,text=stringXY, fg="#000000", bg="#ffffff", command = self.updateChange).grid(row=matrixRow,column=matrixColumn) 
       self.buttons[matrixColumn][matrixRow].append(self.button) 


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

Example of the 8x8 Matrix

答えて

1

以下はあなただけの色と、あなたがリストを使用せずにそれを行うことができます他には何を変更したい場合は、最初は、2例です。 2番目はリストを使用してデリオスが指摘したことを示しています

class App(object): 
    def __init__(self, master): 
     self._master = master 

     for col in range(8): 
      for row in range(8): 
       btn = tk.Button(master, text = '(%d, %d)' % (col, row), bg = 'white') 
       btn['command'] = lambda b = btn: b.config(bg = 'black') 
       btn.grid(row = row, column = col) 

class App(object): 
    def __init__(self, master): 
     self._master = master 
     self._btn_matrix = [] 

     for col in range(8): 
      row_matrix = [] 
      for row in range(8): 
       btn = tk.Button(master, text = '(%d, %d)' % (col, row), bg = 'white', 
           command = lambda x = row, y = col: self.update(x, y)) 
       btn.grid(row = row, column = col) 
       row_matrix.append(btn) 
      self._btn_matrix.append(row_matrix) 

    def update(self, row, col): 
     self._btn_matrix[col][row].config(bg = 'black') 

if __name__ == '__main__': 
    root = tk.Tk() 
    app = App(root) 
    root.mainloop() 
+0

助けてくれてありがとう、あなたの2番目の例を使用し、それは魅力を働いた。本当に助けを感謝し、私は自分自身の残りのアイデアを管理することを希望します。これから明確に学べます! – SgtSafety

0

self.xYループのためにあなたの二重に7,7に設定されており、変更されることはありません。それぞれのボタンで異なるようにするには、updateChangeを2つのパラメータ(x、y)に変更し、ボタンのコマンドとして次のようなものを使用して渡すことができます。 lambda x=matrixColumn y=matrixRow: self.updateChange(x,y)

updateChange

def updateChange(self, x, y): 
    '''...''' 
    self.buttons[x][y].configure(bg="black") 
+0

助けてくれてありがとうございました。私のself.xYは(7,7)になりました。これをしようとすると賢明に考えていませんでした! – SgtSafety

関連する問題