Home > Enterprise >  For loop in tkinter Label return only last line
For loop in tkinter Label return only last line

Time:01-19

I am trying to update a variabletext with new meaning with FOR LOOP but I only get the last line.

team_list = StringVar()
team_list.set('76ers: \nBucks: \nBulls: \nCavaliers: \nCeltics: \nClippers: \nGolden State Warriors: \nGrizzlies: \nHawks: \nHeat: \nHornets: \nJazz: \nKings: \nKnicks: \nLakers: \nMagic: \nMavericks: \nNets: \nNuggets: \nPacers: \nPelicans: \nPistons: \nRaptors: \nRockets: \nSpurs: \nSuns: \nThunder: \nTimberwolves: \nTrail Blazers: \nWizards: ')

def analize():
    if len(t_text.get(1.0, END)) == 1:
        tkinter.messagebox.showinfo(title='Error', message='No text was added')
    else:
        full_list = ['76ers', 'Bucks', 'Bulls', 'Cavaliers', 'Celtics', 'Clippers', 'Golden State Warriors', 'Grizzlies', 'Hawks', 'Heat', 'Hornets', 'Jazz', 'Kings', 'Knicks', 'Lakers', 'Magic', 'Mavericks', 'Nets', 'Nuggets', 'Pacers', 'Pelicans', 'Pistons', 'Raptors', 'Rockets', 'Spurs', 'Suns', 'Thunder', 'Timberwolves', 'Trail Blazers', 'Wizards']
        for team in full_list:
            result = (t_text.get(1.0, END)).count(team)
            team_list.set(str(team)   ': '   str(result))

When trying to print FOR LOOP in terminal, it prints everything as expected, but on tkinter Label variabletext it doesn't work. Just returns last FOR LOOP line.

CodePudding user response:

"team_list" in your last line does not append data, it is written to reset with the latest value. Consider creating an empty list to track counts and then append data for each iteration of the loop.

team_counts = {}

for team in full_list:
        result = (t_text.get(1.0, END)).count(team)
        team_counts[team] = result
    team_list.set('\n'.join(f"{team}: {count}" for team, count in team_counts.items()))
  • Related