A Comprehensive Introduction to Python Programming and ... - MSDL
A Comprehensive Introduction to Python Programming and ... - MSDL
A Comprehensive Introduction to Python Programming and ... - MSDL
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
5.3 Tkinter Variables 45 / 75<br />
from Tkinter import *<br />
import tkFont<br />
root = Tk()<br />
myfont = tkFont.Font(family="arial", size=20, weight=tkFont.BOLD) 5<br />
b1 = But<strong>to</strong>n(root, text="But<strong>to</strong>n 1", font=myfont)<br />
b1.pack()<br />
b2 = But<strong>to</strong>n(root, text="But<strong>to</strong>n 2", font=myfont)<br />
b2.pack()<br />
myfont.config(slant=tkFont.ITALIC) 10<br />
root.mainloop()<br />
This example is much more interesting when coded interactively, so that it is possible<br />
<strong>to</strong> see both but<strong>to</strong>ns reflect the change in the font.<br />
5.3 Tkinter Variables<br />
Tkinter has a special Variable class that all other variable subclasses inherit from.<br />
Various Tkinter widgets have options that rely on the Variable class, such as the<br />
“variable” option for Radiobut<strong>to</strong>ns, the “textvariable” option for the Label, etc.<br />
5.3.1 The Need for New Variables<br />
When the Tkinter variables are used for simple tasks, they do not behave differently<br />
than the regular <strong>Python</strong> variables, apart from the fact that their values have <strong>to</strong> be h<strong>and</strong>led<br />
through method calls, such as get() <strong>and</strong> set(). The choice behind the implementation<br />
of this master variable class is therefore not obvious. However, by taking a<br />
closer look at what the Variable class offers, the motivation behind it becomes much<br />
more apparent. Tkinter variables provide, in true Tkinter style, the possibility <strong>to</strong> add<br />
a callback which will be executed when read <strong>and</strong> write operations are performed on<br />
the variable, <strong>and</strong> also when the value associated with the variable is undefined. This<br />
allows, for example, <strong>to</strong> bind a StringVar() instance <strong>to</strong> a Label widget, which then<br />
au<strong>to</strong>matically updates its caption when the value of the variable changes.<br />
5.3.2 Using Tkinter Variables<br />
Tkinter provides four descendants of the Variable class:<br />
• StringVar<br />
• IntVar<br />
• DoubleVar<br />
• BooleanVar