[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

  • The state method returns or changes the window’s current state—it accepts
    normal, iconic, zoomed (full screen), or withdrawn.


Experiment with these methods on your own to see how they differ. They are also useful
to pop up prebuilt dialog windows dynamically, but are perhaps less practical here.


Example 9-29. PP4E\Gui\Tour\alarm-withdraw.py


same, but hide or show entire window on after() timer callbacks


from tkinter import *
import alarm


class Alarm(alarm.Alarm):
def repeater(self): # on every N millisecs
self.bell() # beep now
if self.master.state() == 'normal': # is window displayed?
self.master.withdraw() # hide entire window, no icon
else: # iconify shrinks to an icon
self.master.deiconify() # else redraw entire window
self.master.lift() # and raise above others
self.after(self.msecs, self.repeater) # reschedule handler


if name == 'main': Alarm().mainloop() # master = default Tk root


This works the same, but the entire window appears or disappears on beeps—you have
to press it when it’s shown. You could add lots of other effects to the alarm, and their
timer-based callbacks technique is widely applicable. Whether your buttons and win-
dows should flash and disappear, though, probably depends less on tkinter technology
than on your users’ patience.


Simple Animation Techniques


Apart from the direct shape moves of the canvasDraw example we met earlier in this
chapter, all of the GUIs presented so far in this part of the book have been fairly static.
This last section shows you how to change that, by adding simple shape movement
animations to the canvas drawing example listed in Example 9-16.


It also demonstrates and expands on the notion of canvas tags—the move operations
performed here move all canvas objects associated with a tag at once. All oval shapes
move if you press “o,” and all rectangles move if you press “r”; as mentioned earlier,
canvas operation methods accept both object IDs and tag names.


But the main goal here is to illustrate simple animation techniques using the time-based
tools described earlier in this section. There are three basic ways to move objects around
a canvas:



  • By loops that use time.sleep to pause for fractions of a second between multiple
    move operations, along with manual update calls. The script moves, sleeps, moves
    a bit more, and so on. A time.sleep call pauses the caller and so fails to return


588 | Chapter 9: A tkinter Tour, Part 2

Free download pdf