# =============================================================================
#                            TkVarDemo.py
#
# Author: Bruno Dufour (bruno.dufour@mail.mcgill.ca)
# URL: http://www.cs.mcgill.ca/~bdufou1
#
# Description: This is a simple application written in Python which has as
#              only purpose to demonstrate how to use Tkinter variables
# =============================================================================

# import the Tkinter module
from Tkinter import *
import sys

# Initialize the Tk module / Create a Tk root window
root = Tk()

# Create a new Tk Integer variable
intVar = IntVar();

# Callback used by the trace_variable method
#    - varName is the Tk name of the variable which
#      was modified. Tk manages its variables with names,
#      and not object references. Luckily for us, you can
#      still access the value of those variables using
#      root.setvar(varName, varValue) and
#      root.getvar(varName)
#    - index is not used in Tkinter (as far as I know).
#      It will always be an empty string. In Tk, this is
#      an integer value which is an array index when the
#      variable is an array (not available in Tkinter)
#    - mode is the kind of modification that triggered
#      the call to this callback method ("w": write,
#      "r": read, "u": undefined).
def writeCallback(varName, index, mode):
    try:
        i = int(root.getvar(varName))
    except ValueError:
        print "Incorrect value -- Resetting to 0"
        root.setvar(varName, 0)


wCallback = intVar.trace_variable("w", writeCallback)

# Set intVar to an incorrect value. This will
# not raise an exception when it is set, but it will
# do so when the value is read (eg through get()).
# In out case, the callback will handle this.
intVar.set("a")
print "Value:", intVar.get()

# Now, remove the callback for the write event
# on intVar.
intVar.trace_vdelete('w', wCallback)

# Set the value as before (still no exception)
intVar.set("a")

# Pause here so that it is easy to see the difference
# between the two versions
print "The next line will raise an exception.(This is normal)"
print "Press the Enter key to continue"
sys.stdin.readline()

# Now generate the exception
print "Value:", intVar.get()

mainloop()