How to use the print function to display to a GUI
You can create a StringVar
that supports write
so you can print to it like a file:
import tkinter as tk
class WritableStringVar(tk.StringVar):
def write(self, added_text):
new_text = self.get() + added_text
self.set(new_text)
def clear(self):
self.set("")
Then using print(... , file=textvar)
you can add to the string variable exactly the same way as printing to the console:
root = tk.Tk()
textvar = WritableStringVar(root)
label = tk.Label(root, textvariable=textvar)
label.pack()
for i in range(4):
print("hello there", file=textvar)
root.mainloop()

note that because print statements (by default) add a newline at the end there will be an extra blank line at the bottom of the label, if it bugs you it can be worked around by removing the newline and reinserting it next addition:
class WritableStringVar(tk.StringVar):
newline = False
def write(self, added_text):
new_text = self.get()
if self.newline: #add a newline from last write.
new_text += "\n"
self.newline = False
if added_text.endswith("\n"): #remove this newline and remember to add one next write.
added_text = added_text[:-1]
self.newline = True
new_text += added_text
self.set(new_text)
def clear(self):
self.set("")
self.newline = False
Either way you can make use of print
s convenient semantics to get text on your GUI.