Tic-tac-toe using python tkinter

坚强是说给别人听的谎言 提交于 2020-12-15 06:07:17

问题


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:


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.



来源:https://stackoverflow.com/questions/54979853/tic-tac-toe-using-python-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!