嗨我正在使用python tkinter并创建了一个按钮列表。我一直试图对它进行编程,所以如果你按一个按钮,它上面的文字会变成X或O(对于游戏tic tac toe)。我尝试使用按钮[“text”] =“text”但它只是出现错误。这是迄今为止的代码:
from tkinter import *
import tkinter.messagebox
tk=Tk()
tk.title("Tic Tac Toe")
bclick = True
buttons = [" "," "," "," "," "," "," "," "," ",]
button_list = [" "," "," "," "," "," "," "," "," ",]
def make_button(n, row, col):
button_list[n] = Button(tk,text=" ",bg='gray',fg='white',height=4,width=8,command=lambda:ttt(buttons, n))
button_list[n].grid(row=row,column=col, sticky=S+N+E+W)
button_list[n] = n
a = 0
B = [0,0,0,1,1,1,2,2,2]
C = [0,1,2,0,1,2,0,1,2]
while a != 9:
b=B[a]
c=C[a]
make_button(a, b, c)
a+=1
def ttt(buttons, n):
global bclick
if buttons[n] == " " and bclick == True:
buttons[n] = "X"
button_list[n]["text"] = "X"
bclick = False
elif buttons[n] == " " and bclick == False:
buttons[n] = "O"
bclick = True
评论错误:
文件“C:\ Users \ Eva Morris \ Documents \ computing \ tic-Tac-Toe.py”,第28行,在ttt button_list [n] [“text”] =“X”TypeError:'int'对象不支持项目分配
问题是你的代码 - 用一个整数覆盖Button-instance:
def make_button(n, row, col):
button_list[n] = Button(tk,text=" ",bg='gray',fg='white',height=4,width=8,command=lambda:ttt(buttons, n))
button_list[n].grid(row=row,column=col, sticky=S+N+E+W)
button_list[n] = n # here you are assigning an INT to button_list[n]
在int
上,不支持通过["text"]
访问。这是关于错误消息告诉你的内容。这就是为什么向我们提供确切的错误很重要。