-1

I am trying to print Labels on a page to confirm players' Names and roles. My code to do so looks like this:

for i in range(1, len(AlivePlayers), 1):
    bar_nein=StringVar()
    player_label=tk.Label(self, textvariable=bar_nein)
    player_label.pack()
    word1=AlivePlayers[i].Name # a string
    word2=" the " # a string
    word3=AlivePlayers[i].Role.keyword # a string
    phrase=word1+word2+word3
    bar_nein.set(phrase)

AlivePlayers is supposed to be an array with a custom object type as defined in section 1 and 2 of the code I attached. No errors occur, but the labels simply don't pop up. An example of what I'm looking for in the result would be: Bob the sheriff (again, as a label on Tkinter).

Full code here

EDIT: As of 2 Aug 2017 I had to rework the code completely and I'm getting what I want (sort of)

T. Corrie
  • 13
  • 5

3 Answers3

0

Actually, the loop does not enter, because you are using a local AlivePlayers list, you have to use python global keyword in order to access the global AlivePlayers ,see this link: Using global variables in a function other than the one that created them

Galalen
  • 64
  • 1
  • 7
  • No. If `AlivePlayers` were local to another function then `len(AlivePlayers)` would raise `NameError`. `AlivePlayers` is actually a global, and it's perfectly valid to access globals from inside a function without using the `global` directive, you just can't _assign` to them. – PM 2Ring Jul 31 '17 at 20:59
  • PM 2Ring: What do you mean I can't `assign` to them? Just looking for more information. – T. Corrie Jul 31 '17 at 21:38
0

Your use of a StringVar() here is accomplishing nothing, since you aren't keeping the var around for later use - and I suspect your problem is due to these unreferenced vars being garbage collected, leaving nothing for the labels to display. (Garbage collection in general works weirdly with Tkinter, since many objects actually exist in the embedded Tcl/Tk environment, where Python cannot tell if they're being used or not.)

Try using text=phrase instead of textvariable=... when creating your labels, to specify their text directly. This will obviously require some rearrangement of code so that phrase exists at the point where the label is created.

jasonharper
  • 9,450
  • 2
  • 18
  • 42
  • Changed it around... But still no luck. The way you have it is probably more concise than what I did so I'll keep it – T. Corrie Jul 31 '17 at 21:35
0

The problem is not the for() as the below example works fine. Time to do some testing which you should do for each block of code anyway.

import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

root=tk.Tk()

alive_players=["One", "Two", "Three"]
for ctr in range(len(alive_players)):
    bar_nein=tk.StringVar()
    player_label=tk.Label(root, textvariable=bar_nein)
    player_label.pack()
    bar_nein.set(alive_players[ctr])

root.mainloop()