Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-How to get the value from tkinter widget and assign it to a variable

Tags:

python

tkinter

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.

like image 825
keshr3106 Avatar asked Jan 22 '14 19:01

keshr3106


People also ask

How do you retrieve data from an entry widget?

To return the data entered in an Entry widget, we have to use the get() method. It returns the data of the entry widget which further can be printed on the console.

How do I get the value of a text widget?

We can get the input from the user in a text widget using the . get() method. We need to specify the input range which will be initially from 1.0 to END that shows the characters starting and ending till the END.

How do you display an output using an entry widget in Python?

Build A Paint Program With TKinter and Python We can use the Tkinter text widget to insert text, display information, and get the output from the text widget. To get the user input in a text widget, we've to use the get() method.

What does Focus_set () do in Tkinter?

Build A Paint Program With TKinter and Python Sometimes, we need to change or modify the focus of any widget in the application which can be achieved by using the focus_set() method. This method sets the default focus for any widget and makes it active till the execution of the program.


2 Answers

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().

like image 57
Bryan Oakley Avatar answered Oct 30 '22 18:10

Bryan Oakley


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)
like image 20
Steven Rumbalski Avatar answered Oct 30 '22 17:10

Steven Rumbalski