7

Basically, I want the body of a Text widget to change when a StringVar does.

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Remove 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'))?
binding on keyrelease will only work when typing. If you paste characters in with the mouse or via a menu, the variable won't get updated. Also, getting up to END will get one extra newline that wasn't added by the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.