Basically, I want the body of a Text widget to change when a StringVar does.
2 Answers
Short version is, you can't. At least, not without doing extra work. The text widget doesn't directly support a variable option.
If you want to do all the work yourself it's possible to set up a trace on a variable so that it keeps the text widget up to date, and you can add bindings to the text widget to keep the variable up to date, but there's nothing built directly into Tkinter to do that automatically.
The main reason this isn't directly supported is that the text widget can have more than just ascii text -- it can have different fonts and colors, embedded widgets and images, and tags.
Comments
I thought of this while working on a project. It's actually really simple:
import tkinter as tk
from tkinter import *
from tkinter.scrolledtext import ScrolledText
def get_stringvar(event):
SV.set(ST1.get("1.0", END))
ST2.replace("1.0", END, SV.get())
root = tk.Tk()
SV = StringVar()
ST1 = ScrolledText(root)
ST1.pack()
ST1.bind('<KeyRelease>', get_stringvar)
ST2 = ScrolledText(root)
ST2.pack()
root.mainloop()
2 Comments
from tkinter import * you are already doing import tkinter as tk. Thought your code works you add an extra step. Why not just do ST2.replace("1.0", 'end', ST1.get("1.0", 'end'))?END will get one extra newline that wasn't added by the user.