Label, Button, and Scale Demo (tkhello4.py)
Our final introductory widget example
introduces the Scale widget and
highlights how widgets can "communicate" with each other using callbacks [such
as resize()]. The text in the Label widget is affected by actions taken on
the Scale widget.
1 #!/usr/bin/env python 2 3 from Tkinter import * 4 5 def resize(ev=None): 6 label.config(font='Helvetica -%d bold' % \ 7 scale.get()) 8 9 top = Tk() 10 top.geometry('250x150') 11 12 label = Label(top, text='Hello World!', 13 font='Helvetica -12 bold') 14 label.pack(fill=Y, expand=1) 15 16 scale = Scale(top, from_=10, to=40, 17 orient=HORIZONTAL, command=resize) 18 scale.set(12) 19 scale.pack(fill=X, expand=1) 20 21 quit = Button(top, text='QUIT', 22 command=top.quit, activeforeground='white', 23 activebackground='red') 24 quit.pack() 25 26 mainloop() |
New features of this script include a resize()
callback function (lines 5-7), which is attached to the Scale. This is
the code that is activated when the slider on the Scale is moved,
resizing the size of the text in the Label.
We also define the size (250 x 150) of the top-level window
(line 10). The final difference between this script and the first three is that
we import the attributes from the Tkinter module into our namespace
with "from Tkinter import *." Although not recommended because
it "pollutes" your namespace, we do it here mainly because this application
involves a great number of references to Tkinter attributes. This would require
use of their fully qualified names for each and every attribute access. By using
the undesired shortcut, we are able to access attributes with less typing and
have code that is easier to read, at some cost.
As you can see from Figure
19-4, both the slider mechanism as well as the current set value show up in
the main part of the window. Figure 19-4
shows the state of the GUI after the user moves the scale/slider to avalue of
36.
0 komentar:
Posting Komentar