Reputation: 413
from tkinter import *
import tkinter as tk
import pyodbc
root1 = tk.Tk()
label1 = tk.Label(root1, text='product A')
entry1 = tk.Entry(root1)
label1.pack(side = tk.TOP)
entry1.pack()
input1= StringVar()
input1.set(entry1.get())
print (input1)
This code is used to assign the value from the input textbox widget to a variable-Input1. However,the value I get is:PY_VAR0 instead of the text in Entry1.
I need to print the input text. Why is PY_VAR0 appearing?
Please help.
Thank you.
Upvotes: 7
Views: 31307
Reputation: 5682
If you want to print the value of a Tkinter variable, you must use the .get()
method to retrieve it, as in
print(input1.get())
Otherwise, you are accessing the variable's name, which is what you're seeing.
When you have a StringVar (or other similar Tkinter variable), you can get the name of the variable by casting to a string, such as
my_string_variable_name = str(input1)
This is the easiest way to get the variable name if you didn't set it when creating the variable. You can set a variable name as follows:
sv = tkinter.StringVar(name='Fred', value='Flintstone') # Note you can set a value, too!
Then
print(str(sv)) # which is what is happening when you say print(sv)
prints out 'Fred', and
print(sv.get())
prints out 'Flintstone'
Upvotes: 2
Reputation: 385900
The problem is that you're getting the value of the entry widget before the user has a chance to type anything, so it will always be the empty string.
If you wait to do the get until after the user enters something, your code will work fine as-is. Though, I don't see any reason to use a StringVar
as it just adds an extra object that serves no real purpose. There's no reason to use a StringVar
with an entry widget unless you need the extra features that a StringVar
gets you -- namely, variable traces.
The reason you are seeing PY_VAR0
is because you must use the get
method to get the value out of an instance of StringVar
. Change your statement to print input1.get()
.
Upvotes: 8
Reputation: 45542
To get the contents of a StringVar
call get()
:
input1.get()
Also, you should bind your StringVar
to the Entry
otherwise the StringVar
won't change with the contents of the Entry
widget:
entry1.config(textvariable=input1)
Or you can bind at construction:
input1 = StringVar()
entry1 = tk.Entry(root1, textvariable=input1)
Upvotes: 4