Skip to content
Advertisement

Buttons in a for loop to update labels in a for loop?

Trying to get individual buttons to update individual labels in tkinter.

Here’s my code:

from tkinter import *

root = Tk()

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

players = []
player = bballPlayer('Tyler','Herro')
players.append(player)
player = bballPlayer('Duncan','Robinson')
players.append(player)
player = bballPlayer('Jimmy','Buckets')
players.append(player)
    
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()

When you run the code there are three buttons in a column next to three labels in the next column over. What I’m trying to do is get it so that each button changes the label next to it.

What happens when I run the code is every button modifies the last label and the other two labels are untouched.

Any help is awesome, thanks!

Advertisement

Answer

This will work for you. I don’t think you understand how the buttons work. Once you .grid() them they are there but when you create a button with the same name you lose reference to the first button. By creating an associative array you have access to the button. The other part you are missing is that you have to pass something to your call back function to let it know which player you are reffering to.

from tkinter import *
from functools import partial

root = Tk()


class bballPlayer:
    def __init__(self, preName, lastName):
        self.preName = preName
        self.lastName = lastName
        self.points = 0

    def incrementOnePoint(self):
        self.points += 1

    def getPoints(self):
        return self.points


players = []
player = bballPlayer('Tyler', 'Herro')
players.append(player)
player = bballPlayer('Duncan', 'Robinson')
players.append(player)
player = bballPlayer('Jimmy', 'Buckets')
players.append(player)


def addOnePoint(num):
    global points_labels
    players[num].incrementOnePoint()
    points_labels[num].config(text=str(players[num].points))


points_buttons = []
points_labels = []
for x in range(len(players)):
    points_buttons.append(Button(root, text='Add Point', command=partial(addOnePoint, x)))
    points_buttons[x].grid(row=x, column=0)
    points_labels.append(Label(root, text=str(players[x].points)))
    points_labels[x].grid(row=x, column=1)


root.mainloop()
10 People found this is helpful
Advertisement