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: