pythontkinterreversi

Building Othello game using Tkinter (Python)


How would I go about building an Othello GUI using tkinter in python? Specifically how would I begin by making the initial four pieces show up? How do I get my board to print out the position of a piece when i select a square? So far it prints out "[189.0, 126.0, 252.0, 189.0]" when click on a piece. I am really just looking for guidance, any help is greatly appreciated! Here is the code I have so far.

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()

Solution

  • Draw the discs by using canvas.create_oval(bbox, **options).

    Use tags to distinguish canvas items:

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

    I'd suggest you tag each element (rectangle and oval) of each cell, with a tag that will allow you to recognize it.

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

    When an item is clicked, you can get all of its tags with

    canvas.gettags(item)
    

    then iterate all of its tags: if the tag starts with "x=" or with "y=", then it contains the row/column information, which you can extract with int(tagname[2:])