井字游戏使用 python tkinter [英] Tic-tac-toe using python tkinter

查看:35
本文介绍了井字游戏使用 python tkinter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 python tkinter 的井字游戏无法正常工作.
井字棋结构是正确的.我只想改变点击事件.
单击任何按钮时仅显示 button9 输出

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()

推荐答案

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

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))

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

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

这篇关于井字游戏使用 python tkinter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆