Reputation: 1910
I'm writing a simple GUI program, and need to load default values from an ini file. I've given names to Entry widget and can get it with nametowidget
method.
However, I can't find a way to access the StringVar bound to the entry widget and update it's value. Using debugger, I can see that StringVar objects dont have a tkinter master, and they dont appear in any widget children. 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)
Upvotes: 4
Views: 2482
Reputation: 22493
You can access the name of the StringVar
associated to a widget by widget["textvariable"]
. Note that this is not the StringVar
itself.
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()
Upvotes: 2
Reputation: 385900
Tkinter widgets have a getvar
and setvar
method which can be used to get and set the value of a variable by its name.
You can get the name of the variable associated with a widget using the cget
method.
Example:
var = tk.IntVar()
entry = tk.Entry(..., textvariable=var)
...
varname = entry.cget("textvariable")
value = entry.getvar(varname)
entry.setvar(varname, value+1)
Upvotes: 3