Search code examples
pythonstringfor-loopuser-interfacemu

'Str' has no attribute 'points'


I'm trying to build a for loop that created multiple labels for some strings in a list, and then next to it have that display a number depending on the strings.

Kind of hard to explain so I will show my code:

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

I'm getting my problem in this section (line 24 to be precise).

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

The error says this:

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'

Any help is very much appreciated, thank you!


Solution

  • You are looping p over players which is defined as a list of strings in players = ['James','Jones','Jr']. You seem you want to use the class bballPlayer but it doesn't look like you are using it; or you overwrote the definition somewhere.