0
votes

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()
1
Please read How to Ask and may take the tour as your question does not fit any of our guidelines. Additional, it appears that you did not put any effort in your question, then why should we put an effort into an answer? - Hille

1 Answers

1
votes

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.