1

I am trying to create a GUI with a text box that automatically appends status messages during the execution of a program. I can use a Label widget with a textvariable to update the text, but as far as I can tell, I can't add a scrollbar to a Label. I can add a scrollbar to a Text widget, but I can't use a textvariable to populate that widget.

I feel like there is a simple answer, but I haven't been able to find it.

This is the working Label without a scrollbar:

self.status_window = tk.Label(
    self.status_window_pane,
    height=5,
    width=50,
    textvariable=self.status_messages,
    relief=GROOVE,
    bg="white",
    fg="black",
    anchor="nw",
    justify=LEFT,
)
Jacob F.
  • 45
  • 6
  • 1
    A `Text` is exactly what you want, but you'd need to call `.insert()` on it to add content rather than using a StringVar. – jasonharper Aug 22 '22 at 15:24
  • `self.statusmessages` implies it has more than one message. Is this a list variable or a tkinter `StringVar`, or something else? – Bryan Oakley Aug 22 '22 at 16:03
  • @BryanOakley - I am collecting the messages into a list and then appending the messages to my StringVar with a newline character. The StringVar that is displayed in the Label is a tkinter StringVar. – Jacob F. Aug 22 '22 at 16:15
  • Why do you need to use a `StringVar` for the messages? Why not just directly update the text widget when you update the list? – Bryan Oakley Aug 22 '22 at 16:22
  • I was using a 'StringVar' for the messages as I could update the variable in a different loop and the GUI would automatically update with the new content. Looks like this should still be available with the 'text.insert()' method. – Jacob F. Aug 22 '22 at 16:33
  • 1
    Yes, you can replace `self.status_messages.set(...)` with `self.the_text_widget.insert(...)` – Bryan Oakley Aug 22 '22 at 16:49

1 Answers1

1

You don't need textvariable to populate a text widget, you can use its insert method:

text = tk.Text(...)

# After some event

text.insert('1.0', content) # 1.0 is the text indice

Some links:

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
  • This works great to get the messages into the text box with a scrollbar. However, when I was using a StringVar, I could call update_idletasks() to asynchronously update the display. Is there a similar way to update using text.insert? As of right now, it only updates when the calling function completes rather than throughout the calling function. – Jacob F. Aug 22 '22 at 16:13
  • 1
    @JacobF. It should still work, do you have an example you can show using `update_idletasks` where it does n't work? – Delrius Euphoria Aug 22 '22 at 16:23
  • 1
    you are correct, it does still work. Just a simple error on my end. – Jacob F. Aug 22 '22 at 17:25