How can I include static text in a StringVar() and still have it update to variable changes?

限于喜欢 提交于 2020-01-24 15:57:05

问题


I would like to create a StringVar() that looks something like this:

someText = "The Spanish Inquisition" # Here's a normal variable whose value I will change

eventually

TkEquivalent = StringVar() # and here's the StringVar()

TkEquivalent.set(string(someText)) #and here I set it equal to the normal variable. When someText changes, this variable  will too...

HOWEVER:

TkEquivalent.set("Nobody Expects " + string(someText))

If I do this, the StringVar() will no longer automatically update! How can I include that static text and still have the StringVar() update to reflect changes made to someText?

Thanks for your help.


回答1:


A StringVar does not bind with a Python name (what you'd call a variable), but with a Tkinter widget, like this:

a_variable= Tkinter.StringVar()
an_entry= Tkinter.Entry(textvariable=a_variable)

From then on, any change of a_variable through its .set method will reflect in the an_entry contents, and any modification of the an_entry contents (e.g. by the user interface) will also update the a_variable contents.

However, if that is not what you want, you can have two (or more) references to the same StringVar in your code:

var1= var2= Tkinter.StringVar()
var1.set("some text")
assert var1.get() == var2.get() # they'll always be equal


来源:https://stackoverflow.com/questions/2770409/how-can-i-include-static-text-in-a-stringvar-and-still-have-it-update-to-varia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!