`I made this Tic-Tac-Toe game first, by using user input in the console here: https://pastebin.com/6zLjrWcf , and now new and improved using Tkinter:
import tkinter as tk
from tkinter import ttk
import time
def create_button(relx, rely):
button = tk.Button(width=10, height=2, command=lambda: callback(button))
button.place(relx=relx, rely=rely)
return button
def check_win():
if (buttons[0]['text'] == buttons[1]['text'] == buttons[2]['text'] != '') or \
(buttons[3]['text'] == buttons[4]['text'] == buttons[5]['text'] != '') or \
(buttons[6]['text'] == buttons[7]['text'] == buttons[8]['text'] != '') or \
(buttons[0]['text'] == buttons[3]['text'] == buttons[6]['text'] != '') or \
(buttons[1]['text'] == buttons[4]['text'] == buttons[7]['text'] != '') or \
(buttons[2]['text'] == buttons[5]['text'] == buttons[8]['text'] != '') or \
(buttons[2]['text'] == buttons[4]['text'] == buttons[6]['text'] != '') or \
(buttons[0]['text'] == buttons[4]['text'] == buttons[8]['text'] != ''):
return True
else:
return False
def callback(button):
global turn, x
if x == 1:
time.sleep(1)
game.quit()
invalid['text'] = ''
if button['text'] != '':
invalid['text'] = 'Invalid space try again'
return
button['text'] = turn
if check_win():
invalid['text'] = 'Player ' + turn + ' WINS!!!!!'
x = 1
turn = ('0' if turn == 'X' else 'X')
label_button['text'] = 'PLAYER ' + turn + '\'S TURN.'
x = 0
turn = 'X'
game = tk.Tk()
game.title('TicTacToe')
game.geometry('700x500')
buttons = []
for i in range(1, 10):
button_created = create_button(0.25 if i / 3 <= 1 else 0.45 if i / 3 <= 2 else 0.65, 0.2 if i in [1, 4, 7] else
0.4 if i in [2, 5, 8] else 0.6)
buttons.append(button_created)
label_button = ttk.Button(game, text='PLAYER ' + turn + '\'S TURN.', style='Fun.TButton', width=20, state='disabled')
label_button.pack(pady=30)
invalid = tk.Label(text='')
invalid.place(relx=0.4, rely=0.12)
game.mainloop()
My main question is if there is a way to compact check_win()? Also please review the rest of the code.