2016-06-10 139 views
1

我是Python的初學者,我正嘗試使用tkinter編寫tictactoe遊戲。我的班級Cell延伸Tkinter.LabelCell類包含數據字段emptyLabel,xLabeloLabel。這是到目前爲止我的代碼爲Cell類:用鼠標點擊更新tkinter標籤

from tkinter import * 

class Cell(Label): 
    def __init__(self,container): 
     super().__init__(container) 
     self.emptyImage=PhotoImage(file="C:\\Python34\\image\\empty.gif") 
     self.x=PhotoImage(file="C:\\Python34\\image\\x.gif") 
     self.o=PhotoImage(file="C:\\Python34\\image\\o.gif") 

    def getEmptyLabel(self): 
     return self.emptyImage 

    def getXLabel(self): 
     return self.x 

    def getOLabel(self): 
     return self.o 

和我的主類是如下:

from tkinter import * 
from Cell import Cell 

class MainGUI: 
    def __init__(self): 
     window=Tk() 
     window.title("Tac Tic Toe") 

     self.frame1=Frame(window) 
     self.frame1.pack() 

     for i in range (3): 
      for j in range (3): 
       self.cell=Cell(self.frame1) 
       self.cell.config(image=self.cell.getEmptyLabel()) 

       self.cell.grid(row=i,column=j) 

     self.cell.bind("<Button-1>",self.flip) 

     frame2=Frame(window) 
     frame2.pack() 
     self.lblStatus=Label(frame2,text="Game Status").pack() 

     window.mainloop() 

    def flip(self,event): 
     self.cell.config(image=self.cell.getXLabel()) 

MainGUI() 

代碼對細胞的3x3顯示一個空的細胞圖像,但是當我點擊單元格將空單元格圖像更新爲X圖像。它目前只發生在第3行第3列的空標籤上。

我的問題是:如何更改鼠標單擊上的標籤?

回答

2

您繼續重新指定self.cell,然後當該部分完成後,將鼠標按鈕綁定到最後一個單元格。將鼠標按鈕綁定到循環中的每個單元格。

回調函數也是硬編碼的,僅查看self.cell,您不斷重新指定最後只有最後一個。除了將鼠標按鈕綁定到每個單元之外,還必須更改回調函數以查看正確的單元格。

__init__

for i in range (3): 
    for j in range (3): 
     cell=Cell(self.frame1) 
     cell.config(image=self.cell.getEmptyLabel()) 

     cell.grid(row=i,column=j) 

     cell.bind("<Button-1>", lambda event, cell=cell: self.flip(cell)) 

,或在不使用lambda

for i in range (3): 
    for j in range (3): 
     cell=Cell(self.frame1) 
     cell.config(image=self.cell.getEmptyLabel()) 

     cell.grid(row=i,column=j) 

     def temp(event, cell=cell): 
      self.flip(cell) 

     cell.bind("<Button-1>", temp) 

flip

def flip(self, cell): 
    self.cell.config(image=cell.getXLabel()) 
+0

感謝你的代碼和它的作品,但你可以解釋或許給一些線索,所以我可以googling什麼cell.bind(「 「,lambda事件,細胞=細胞:self.flip(細胞)),我明白按鈕1,但休息代碼我不,謝謝 – ebil

+0

如何,如果我避免使用lambda?有一種方法??,謝謝 – ebil

+0

@ebil - 'lambda'定義了一個內聯匿名函數。這一個採用當前單元格的默認參數的「事件」(鼠標點擊)和「單元格」。在這種情況下,此缺省參數是必需的 - 沒有它,只有單擊時纔會查找「單元格」,此時它將始終是第3行第3列中的單元格。 – TigerhawkT3