2016-06-10 157 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