1

I am using a StringVar to update a label on a GUI.

I am using the set method to update the value, but the text never shows up when the application is run.

I am able use the get method (the final print statement, as seen below) and see that the value that has been passed into it, but it still doesn't show up on my window. I am using a mac with Spyder.

class Application(tk.Frame):
    def __init__(self, bud, master=None):
        super().__init__(master)
        self.bud = bud
        self.master = master
        self.pack()
        self.bud.update_all()
        self.r = 1
        self.create_widgets()

    def create_widgets()
        trans = [tk.StringVar() for c in self.bud.categories]

        for i, c in enumerate(self.bud.categories):
            tk.Label(self, text = c.name, anchor = "w").grid(row = self.r, column = 0)
            tk.Label(self, textvariable = trans[i],fg = "black").grid(row = self.r, column = 1)
            trans[i].set("Hello")
            self.r +=1
        print(trans[i].get())

This section is run outside the class in the main script

root = tk.Tk()
app = Application(bud, master = root)
app.mainloop()
stovfl
  • 14,998
  • 7
  • 24
  • 51
  • Fixing the errors it works for me as expected, read [tkinter-checkbutton-text-wont-show-up](https://stackoverflow.com/questions/59338948/tkinter-checkbutton-text-wont-show-up) – stovfl Dec 28 '19 at 23:28

1 Answers1

0

The problem is you're using loop variable as values for the widget options which change every iteration of the loop. I think the following will avoid the problem by using a helper function — but can't verify this because you didn't provide a minimal reproducible example in your question.

Note you also left out the self argument on the create_widgets() method.

    def create_widgets(self):

        # Local helper function.
        def create_labels(name, var, row):
            tk.Label(self, text=name, anchor="w").grid(row=row, column=0)
            tk.Label(self, textvariable=var, fg="black").grid(row=row, column=1)

        trans = [tk.StringVar() for _ in self.bud.categories]

        for i, c in enumerate(self.bud.categories):
            create_labels(c.name, trans[i], self.r)
            trans[i].set("Hello")
            self.r +=1
            print(trans[i].get())
martineau
  • 119,623
  • 25
  • 170
  • 301