'Str' 没有属性 'points'

'Str' has no attribute 'points'

我正在尝试构建一个 for 循环,为列表中的某些字符串创建多个标签,然后在它旁边根据字符串显示一个数字。

有点难以解释,所以我会展示我的代码:

from tkinter import *

root = Tk()

class bballPlayer:
    def __init__(self):
        self.points = 0
    
    def incrementOnePoint(self):
        self.points += 1
    
    def getPoints(self):
        return self.points

players = ['James','Jones','Jr']
    
def addOnePoint():
    p.incrementOnePoint()
    global pointslabel
    pointslabel.config(text=str(p.points))

rowNumber = 0
for p in players:
    pointslabel = Label(root, text=str(p.points))
    pointslabel.grid(row=rowNumber, column=1)
    rowNumber += 1

rowNumber = 0
for p in players:
    btn = Button(root, text='Add Point', command=addOnePoint)
    btn.grid(row=rowNumber, column=0)
    rowNumber += 1

root.mainloop()

我在这部分遇到了问题(准确地说是第 24 行)。

rowNumber = 0
for p in players:
    pointslabel = Label(root, text=str(p.points))
    pointslabel.grid(row=rowNumber, column=1)
    rowNumber += 1

错误是这样说的:

Traceback (most recent call last):
  File "/Users/*****/mu_code/testcode.py", line 24, in <module>
    pointslabel = Label(root, text=str(p.points))
AttributeError: 'str' object has no attribute 'points'

非常感谢任何帮助,谢谢!

你在 players 上循环 p,它被定义为 players = ['James','Jones','Jr'] 中的字符串列表。您似乎想使用 class bballPlayer,但它看起来不像您在使用它;或者你在某处覆盖了定义。