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()
frame = tk.Frame(root, bg="white")

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:

    # 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:

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)


This is what it looks like:

An image of the tkinter window

An image of the tkinter window where X has won

An image of the tkinter window where there is a draw

  • 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
    Oct 10 at 11:41


Your Answer

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

Browse other questions tagged or ask your own question.