Tic-tac-toe使用python tkinter

问题描述 投票:0回答:1

使用python tkinter的Tic-tac-toe游戏无法正常工作。 Tic-tac-toe结构是正确的。我只是想改变点击事件。 单击任意按钮时仅显示button9输出

每次单击任何按钮,都会显示此输出

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()
python-3.x tkinter buttonclick
1个回答
0
投票

常见的错误。 lambda函数使用分配给i的最后一个值,因此每个lambda将使用i =。!button9。将lambda函数更改为:

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

这将使lambda在创建lambda时使用i的值。

© www.soinside.com 2019 - 2024. All rights reserved.