我是 Python 初学者,正在尝试使用 tkinter
编写井字游戏。我的类名为 Cell
扩展了 Tkinter.Label
。 Cell
类包含数据字段emptyLabel
、xLabel
和oLabel
。这是迄今为止我的 Cell
类代码:
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
我的主要类(class)如下:
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 列的空标签上。
我的问题是:如何更改鼠标单击时的标签?
最佳答案
您不断重新分配self.cell
,然后当该部分完成后,您将鼠标按钮绑定(bind)到最后一个单元格。将鼠标按钮绑定(bind)到循环内的每个单元格。
回调函数也被硬编码为仅查看self.cell
,您不断地重新分配它,最终只得到最后一个。除了将鼠标按钮绑定(bind)到每个单元格之外,您还必须更改回调函数以查看正确的单元格。
在__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)
在翻转
中:
def flip(self, cell):
self.cell.config(image=cell.getXLabel())
关于python - 通过鼠标单击更新 tkinter 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37748050/