2016-07-05 345 views
1

我正在使用tkinter創建一個8x8按鈕矩陣,當按下單個按鈕時添加到最終列表(例如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

下面是兩個例子,第一個是,如果你只是想改變顏色,沒有別的,那麼你可以不用使用列表。第二個涉及到使用列表,並演示利希特指出了什麼

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

感謝您的幫助,使用了第二個例子,它發揮了魅力。真的很感謝幫助,希望我能自己管理其餘的想法。肯定會從中學習! – SgtSafety

0

self.xY在你的雙for循環,並沒有改變設置爲7,7。如果您希望每個按鈕都有所不同,您可能需要將updateChange更改爲兩個參數(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