Search code examples
pythontkinter

get StringVar bound to Entry widget


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)

Solution

  • 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)