使用 Tkinter 构建黑白棋游戏 (Python)

Building Othello game using Tkinter (Python)

我将如何在 python 中使用 tkinter 构建黑白棋图形用户界面?具体来说,我将如何开始让最初的四件作品出现?当我 select 一个正方形时,如何让我的棋盘打印出棋子的位置?到目前为止,当点击一块时它会打印出“[189.0, 126.0, 252.0, 189.0]”。我真的只是在寻找指导,非常感谢任何帮助!这是我目前的代码。

import tkinter
class RA:
    def __init__(self):
        self._columns = 8
        self._rows = 8
        self._root = tkinter.Tk()
        self._canvas = tkinter.Canvas(master = self._root,
                                      height = 500, width = 500,
                                      background = 'green')
        self._canvas.pack(fill = tkinter.BOTH, expand = True)
        self._canvas.bind('<Configure>',self.draw_handler)


    def run(self):
        self._root.mainloop()

    def draw(self):
        for c in range(self._columns):
            for r in range(self._rows):
                x1 = c * (column_width)
                y1 = r * (row_height)
                x2 = x1 + (column_width)
                y2 = y1 + (row_height)

    def clicked(self,event: tkinter.Event):
        x = event.x
        y = event.y
        coordinates = self._canvas.coords("current")
        print(coordinates)

    def draw(self):
        self._canvas.delete(tkinter.ALL)
        column_width = self._canvas.winfo_width()/self._columns
        row_height = self._canvas.winfo_height()/self._rows
        for  x in range(self._columns):
            for y in range(self._rows):
                x1 = x * column_width
                y1 = y * row_height
                x2 = x1 + column_width
                y2 = y1 + row_height
                r = self._canvas.create_rectangle(x1,y1,x2,y2,fill = 'blue')
                self._canvas.tag_bind(r,'<ButtonPress-1>',self.clicked)

                self._canvas.create_rectangle(x1,y1,x2,y2)
        self._canvas.bind('<Configure>',self.draw_handler)


    def draw_handler(self,event):
        self.draw()


r = RA()
r.run()

使用canvas.create_oval(bbox, **options)绘制圆盘。

使用标签区分canvas项:

Tags are symbolic names attached to items. Tags are ordinary strings, and they can contain anything except whitespace.

我建议您为每个单元格的每个元素(矩形和椭圆形)添加标签,让您能够识别它。

item = canvas.create_oval(x1, x2, y1, y2, tags=("x=1","y=3"))

当一个项目被点击时,您可以通过

获取它的所有标签
canvas.gettags(item)

然后遍历其所有标签:如果标签以"x=""y="开头,则它包含row/column信息,您可以使用[=15=提取这些信息]