How to use a StringVar object in an Entry widget in Tkinter?


A StringVar object in Tkinter can help manage the value of a widget such as an Entry widget or a Label widget. You can assign a StringVar object to the textvariable of a widget. For example,

data = ['Car', 'Bus', 'Truck', 'Bike', 'Airplane']

var = StringVar(win)

my_spinbox = Spinbox(win, values=data, textvariable=var)

Here, we created a list of strings followed by a StringVar object "var". Next, we assigned var to the textvariable of a Spinbox widget. To get the current value of the Spinbox, you can use var.get().

Example

The following example demonstrates how you can use a StringVar object in an Entry widget.

from tkinter import *

top = Tk()
top.geometry("700x300")
top.title("StringVar Object in Entry Widget")

var = StringVar(top)

def submit():
   Label2.config(text="Your User ID is: " +var.get(), font=("Calibri,15,Bold"))

Label1 = Label(top, text='Your User ID:')
Label1.grid(column=0, row=0, padx=(20,20), pady=(20,20))

myEntry = Entry(top, textvariable=var)
myEntry.grid(column=1, row=0, padx=(20,20), pady=(20,20))

myButton = Button(top, text="Submit", command=submit)
myButton.grid(column=2, row=0)

Label2 = Label(top, font="Calibri,10")
Label2.grid(column=0, row=1, columnspan=3)

top.mainloop()

Output

It will produce the following output −

Updated on: 26-Oct-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements