best way to increment an IntVar?
Dave Angel
davea at ieee.org
Fri Jun 25 13:14:55 EDT 2010
Alan G Isaac wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">On
> 6/24/2010 1:59 AM, Dennis Lee Bieber wrote:
>> It is NOT a numeric "variable" in Python realms.
>
> Sure, but why does it not behave more like one?
> It seems both obvious and desirable, so I'm
> guessing there is a good reason not to do it.
>
>> So var+=increment can't be used because Python would rebind the name
>> var to a new object
>
>>>> import Tkinter as tk
>>>>
>>>> class IntVar2(tk.IntVar):
> ... def __iadd__(self, val):
> ... self.set(self.get()+val)
> ... return self
> ...
>>>> root = tk.Tk()
>>>> myintvar2 = IntVar2()
>>>> temp = myintvar2
>>>> myintvar2 += 5
>>>> print(myintvar2.get(),myintvar2 is temp)
> (5, True)
>
> Alan Isaac
>
A real Python integer is immutable. But for tkinter, you want something
that can change. So they define an object that can be changed. But the
default behavior of += is to assign a new object with the new value,
rather than changing the previous object.
DaveA
More information about the Python-list
mailing list