Search code examples
pythontkintervariable-length

Finding the length of a stringvar


I am trying to make a function that will add text to a text box if the variable behind it is empty. I was attempting to do this using the .len() function, but I get an

AttributeError: 'StringVar' object has no attribute 'length'. 

My code is as follows:

line1var = StringVar()

line1var.set("")

def tobeplaced(value):

    global line1var

    if line1var.length() == 0:

        txtReceipt.insert(END, value)

foo = Button(root, text="foo", command=lambda : tobeplaced("foo")).pack()

What do?


Solution

  • A Tkinter StringVar doesn't have a .len or .length method. You can access the associated string with the get method, and get the length of that string with the standard Python built-in len function, eg

    if len(line1var.get()) == 0:
    

    but it's cleaner (and more efficient) to do

    if not line1var.get():
    

    since an empty string is false-ish.

    Here's a small (Python 3) demo:

    import tkinter as tk
    
    root = tk.Tk()
    
    label_text = tk.StringVar()
    label = tk.Label(textvariable=label_text)
    label.pack()
    
    def update():
        text = label_text.get()
        if not text:
            text = 'base'
        else:
            text += '.'
        label_text.set(text)
    
    b = tk.Button(root, text='update', command=update)
    b.pack()
    
    root.mainloop()
    

    BTW, you should not do

    foo = Button(root, text="foo", command=lambda : tobeplaced("foo")).pack()
    

    The .pack method (and the related .grid and .place methods) returns None, so the above statement assigns None to foo. To assign the widget to foo you need to do the assignment and the packing in separate statements, eg

    foo = Button(root, text="foo", command=lambda : tobeplaced("foo"))
    foo.pack()