2
\$\begingroup\$

I recently made this tic-tac-toe program using tkinter, but I am quite new to tkinter, so I would be grateful for tips on how to improve the program. (Note that the actual tic-tac-toe logic is being done by the python-tictactoe library.)

This is my code:

import tkinter as tk

from tictactoe import Board
from tictactoe import X, O

root = tk.Tk()
root.geometry("400x400")
frame = tk.Frame(root, bg="white")
frame.pack()

board = Board()


def convert_to_str(player):
    return "X" if player == X else "O"


def push(i):
    pos = ((i + 1) % 3, i // 3)

    if board.is_empty(pos) and board.result() is None:
        squares[i].config(text=convert_to_str(board.turn))
        board.push(pos)

    # if there is a winner (use bool, because a draw is 0; so True only if board.result is 1 or 2)
    if bool(board.result()):
        for square in squares:
            if square.cget("text") == convert_to_str(board.result()):
                square.config(bg="green", fg="gold")

    # if it is a draw
    elif board.result() == 0:
        for square in squares:
            square.config(bg="yellow")


squares = [tk.Button(frame, text=" ", font=("Courier", 50), bg="white", command=lambda i=i: push(i)) for i in range(9)]

for i, square in enumerate(squares):
    square.grid(row=(i + 1) % 3, column=i // 3)

tk.mainloop()

This is what it looks like:

GUI:
An image of the tkinter window

Win:
An image of the tkinter window where X has won

Draw:
An image of the tkinter window where there is a draw

\$\endgroup\$
1
  • 1
    \$\begingroup\$ For a win wouldn't it be better if you only use the green background on the 3 squares that constituted the win? \$\endgroup\$
    – Booboo
    Commented Oct 10, 2023 at 11:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.