Mitesh Masurkar
Mitesh Masurkar

Reputation: 1

Tic-tac-toe using python tkinter

Tic-tac-toe game using python tkinter is not working correctly.
Tic-tac-toe structure is correct. I just want to change the click event.
Only button9 output shown when click to any button

Every time I click any button this output is shown

from tkinter import *

    bclick = True


    tk = Tk()
    tk.title("Tic Tac toe")
    tk.geometry("300x400")
    n = 9
    btns = []


    def ttt(button):
        global bclick
        print(button)
        if button["text"] == "" and bclick == True:
            print("if")
            button.config(text="X")
            bclick = False
        elif button["text"] == "" and bclick == False:
            print("else")
            button["text"] = "0"
            bclick = True


    for i in range(9):
        btns.append(Button(font=('Times 20 bold'), bg='white', fg='black', height=2, width=4))
    row = 1
    column = 0
    index = 1
    print(btns)
    buttons = StringVar()
    for i in btns:

        i.grid(row=row, column=column)
        i.config(command=lambda: ttt(i))
        print(i, i["command"])
        column += 1
        if index % 3 == 0:
            row += 1
            column = 0
        index += 1
    tk.mainloop()

Upvotes: 0

Views: 5429

Answers (1)

figbeam
figbeam

Reputation: 7176

Common misstake. The lambda function is using the last value assigned to i so every lambda will use i=.!button9. change the lambda function to:

i.config(command=lambda current_button=i: ttt(current_button))

which will make lambda use the value of i when the lambda was created.

Upvotes: 2

Related Questions