python - 通过鼠标单击更新 tkinter 标签

标签 python tkinter

我是 Python 初学者,正在尝试使用 tkinter 编写井字游戏。我的类名为 Cell 扩展了 Tkinter.LabelCell 类包含数据字段emptyLabelxLabeloLabel。这是迄今为止我的 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/

相关文章:

python - 生成具有理解力的常量列表?

python - 为 python 文件设置一致的主目录

python - 如何在 PyX 中生成任何颜色

python - 如何确保我的 ttk.Entry 的无效状态在失去焦点时不被清除?

python - 如果我使用bind_all,我可以对某些小部件进行异常(exception)处理吗?

python - 计算 X 和 Y 坐标之间的值

python - 涉及pyqt时文件复制太慢

python - [Python]根据下拉菜单选项更新 GUI

python - 自动恢复最小化的 tkinter 窗口

python - 线程在退出 tk 窗口时不会关闭