TypeError: unsupported operand type(s) for +: ‘StringVar’ and ‘str’ in Python

TypeError: can only concatenate str (not “StringVar”) to str in Python.

Using the STRINGVAR variable as STRING cause the error in Python.

I am using textbox out stringvar output for merge the value into String variable cause the errors:


Program:


from tkinter import *

def validateLogin():
    varusername = "hello "+username
    print (varusername)

#Main program windows - Main window 
tkWindow = Tk()  
tkWindow.geometry('300x160+500+200')  
tkWindow.title('Test Utility')
#username label and text entry box
usernameLabel = Label(tkWindow, text=r"User Name")
usernameLabel.grid(row=5, column=5)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username)
usernameEntry.grid(row=5, column=6)

loginButton = Button(tkWindow, text="Login", command=validateLogin)
loginButton.grid(row=8, column=6, padx=10, pady=20)  


tkWindow.mainloop()

Error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\pythonuser\Anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
    return self.func(*args)
  File "C:\Users\pythonuser\Desktop\untitled10.py", line 13, in validateLogin
    varusername = "hello "+username
TypeError: can only concatenate str (not "StringVar") to str

Solution:

Use the username.get() function to get the value in String


from tkinter import *


def validateLogin():
    varusername = "hello "+username.get()
    print (varusername)


#Main program windows - Main window 
tkWindow = Tk()  
tkWindow.geometry('300x160+500+200')  
tkWindow.title('Test Utility')
#username label and text entry box
usernameLabel = Label(tkWindow, text=r"User Name")
usernameLabel.grid(row=5, column=5)
username = StringVar()
usernameEntry = Entry(tkWindow, textvariable=username)
usernameEntry.grid(row=5, column=6)

loginButton = Button(tkWindow, text="Login", command=validateLogin)
loginButton.grid(row=8, column=6, padx=10, pady=20)  


tkWindow.mainloop()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.