1
我是Python的初學者,我正嘗試使用tkinter
編寫tictactoe遊戲。我的班級Cell
延伸Tkinter.Label
。 Cell
類包含數據字段emptyLabel
,xLabel
和oLabel
。這是到目前爲止我的代碼爲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列的空標籤上。
我的問題是:如何更改鼠標單擊上的標籤?
感謝你的代碼和它的作品,但你可以解釋或許給一些線索,所以我可以googling什麼cell.bind(「 「,lambda事件,細胞=細胞:self.flip(細胞)),我明白按鈕1,但休息代碼我不,謝謝 –
ebil
如何,如果我避免使用lambda?有一種方法??,謝謝 – ebil
@ebil - 'lambda'定義了一個內聯匿名函數。這一個採用當前單元格的默認參數的「事件」(鼠標點擊)和「單元格」。在這種情況下,此缺省參數是必需的 - 沒有它,只有單擊時纔會查找「單元格」,此時它將始終是第3行第3列中的單元格。 – TigerhawkT3