Retrieval of widget property values

Peter Otten __peter__ at web.de
Wed Oct 27 08:11:24 EDT 2010


Jah_Alarm wrote:

> hi, here's my problem:
> 
> let's say I have a function that uses some widget's property. How canI
> retireve the value of this property?
> 
> For example,
> 
> PopSize=IntVar();
> 
> popsize=Entry(root,width=10,textvariable=PopSize)
> 
> def rand_opo_gen (self,event):
>       popsize_start=#need to get the textvariable value from Entry
> popsize, not variable PopSize!
>       pop1=random.random(popsize_start*2)
> 
> Another option, of course, is that the variable PopSize acquires the
> value from Entry, but I can't see how to do it either

In Tkinter you normally access properties of a widget with widget[propname]. 
This doesn't help here because it will only give you a name made up by 
Tkinter instead of the actual IntVar instance.

Therefore the easiest approach is to keep a reference to the IntVar instance 
and invoke IntVar.get()/set(new_value). A self-contained example:

import Tkinter as tk

root = tk.Tk()
size_var = tk.IntVar()
size_var.set(42)

size_entry = tk.Entry(root, textvariable=size_var)
size_entry.pack()

def show_size():
    print size_var.get()

show_button = tk.Button(root, text="show size", command=show_size)
show_button.pack()

def times_two():
    new_value = size_var.get()*2
    size_var.set(new_value)

timestwo_button = tk.Button(root, text="times two", command=times_two)
timestwo_button.pack()

root.mainloop()

Peter



More information about the Python-list mailing list