如果按钮在列表中,如何编辑按钮上的文本?

时间:2018-09-17 17:44:11

标签: python-3.x list button tkinter

嗨,我正在使用python tkinter并创建了按钮列表。我一直在尝试对其进行编程,因此,如果您按下按钮,则其文本将变为X或O(对于游戏井字游戏)。我尝试使用button [“ 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”,在ttt button_list [n] [“ text”] =“ X”中的第28行TypeError:'int'对象不支持项目分配

1 个答案:

答案 0 :(得分:1)

问题出在您的代码上-您用整数覆盖了Button实例:

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"]进行的访问。那就是错误消息告诉您的内容。因此,向我们提供确切的错误要点

相关问题