Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect a variable to Entry widget?

I'm trying to associate a variable with a Tkinter entry widget, in a way that:

  1. Whenever I change the value (the "content") of the entry, mainly by typing something into it, the variable automatically gets assigned the value of what I've typed. Without me having to push a button "Update value " or something like that first.

  2. Whenever the variable gets changed (by some other part of the programm), I want the entry value displayed to be adjusted automatically. I believe that this could work via the textvariable.

I read the example on http://effbot.org/tkinterbook/entry.htm, but it is not exactly helping me for what I have in mind. I have a feeling that there is a way of ensuring the first condition with using entry's "validate". Any ideas?

like image 719
Sano98 Avatar asked Mar 26 '10 14:03

Sano98


People also ask

How do you take input from an entry widget?

An Entry widget in Tkinter is nothing but an input widget that accepts single-line user input in a text field. 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 you display an output using an entry widget in Python?

Type something in the text widget and click the "Print" button to display the output.


1 Answers

I think you want something like this. In the example below, I created a variable myvar and assigned it to be textvariable of both a Label and Entry widgets. This way both are coupled and changes in the Entry widget will reflect automatically in Label.

You can also set trace on variables, e.g. to write to stdout.

from tkinter import *


root = Tk()
root.title("MyApp")

myvar = StringVar()

def mywarWritten(*args):
    print "mywarWritten",myvar.get()

myvar.trace("w", mywarWritten)

label = Label(root, textvariable=myvar)
label.pack()

text_entry = Entry(root, textvariable=myvar)
text_entry.pack()

root.mainloop()
like image 154
Anurag Uniyal Avatar answered Oct 19 '22 08:10

Anurag Uniyal