[英]get StringVar bound to Entry widget
I'm writing a simple GUI program, and need to load default values from an ini file. 我正在编写一个简单的GUI程序,需要从ini文件中加载默认值。 I've given names to Entry widget and can get it with
nametowidget
method. 我已经为Entry小部件指定了名称,并且可以使用
nametowidget
方法获取它。
However, I can't find a way to access the StringVar bound to the entry widget and update it's value. 但是,我找不到访问绑定到条目小部件的StringVar并更新其值的方法。 Using debugger, I can see that StringVar objects dont have a tkinter master, and they dont appear in any widget children.
使用调试器,我可以看到StringVar对象没有tkinter母版,也没有出现在任何小部件子代中。 So is what I'm trying to do possible ?
那我想做的可能吗? Or is there a workaround ?
还是有解决方法?
Below is the concerned function. 以下是相关功能。
def load_data(data_file):
"""
Read an ini file and update related values
:param data_file:
:return:
"""
conf = configparser.ConfigParser()
try:
conf.read(data_file)
for section in conf.sections():
try:
container = SECTIONS[section]
for key in conf[section]:
widget = container.nametowidget(key)
widget.set(conf[section][key])
except KeyError:
pass
except configparser.Error as e:
print(e)
You can access the StringVar
associated to a widget by widget["textvariable"]
. 您可以通过
widget["textvariable"]
访问与窗口widget["textvariable"]
关联的StringVar
。
import tkinter as tk
root = tk.Tk()
a = tk.StringVar()
a.set(0)
b = tk.Entry(root,textvariable=a)
b.pack()
print (b["textvariable"])
root.mainloop()
Tkinter widgets have a getvar
and setvar
method which can be used to get and set the value of a variable by its name. Tkinter小部件具有
getvar
和setvar
方法,可通过其名称获取和设置变量的值。
You can get the name of the variable associated with a widget using the cget
method. 您可以使用
cget
方法获取与窗口小部件关联的变量的名称。
Example: 例:
var = tk.IntVar()
entry = tk.Entry(..., textvariable=var)
...
varname = entry.cget("textvariable")
value = entry.getvar(varname)
entry.setvar(varname, value+1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.