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

(yzsuai) #1

Figure 8-27. Manual check button state window


Manually maintained state toggles are updated on every button press and are printed
when the GUI exits (technically, when the mainloop call returns); it’s a list of Boolean
state values, which could also be integers 1 or 0 if we cared to exactly imitate the
original:


C:\...\PP4E\Gui\Tour> python demo-check-manual.py
[False, False, True, False, True, False, False, False, True, False]

This works, and it isn’t too horribly difficult to manage manually. But linked tkinter
variables make this task noticeably easier, especially if you don’t need to process check
button states until some time in the future. This is illustrated in Example 8-24.


Example 8-24. PP4E\Gui\Tour\demo-check-auto.py


check buttons, the easy way


from tkinter import *
root = Tk()
states = []
for i in range(10):
var = IntVar()
chk = Checkbutton(root, text=str(i), variable=var)
chk.pack(side=LEFT)
states.append(var)
root.mainloop() # let tkinter keep track
print([var.get() for var in states]) # show all states on exit (or map/lambda)


This looks and works the same way, but there is no command button-press callback
handler at all, because toggle state is tracked by tkinter automatically:


C:\...\PP4E\Gui\Tour> python demo-check-auto.py
[0, 0, 1, 1, 0, 0, 1, 0, 0, 1]

The point here is that you don’t necessarily have to link variables with check buttons,
but your GUI life will be simpler if you do. The list comprehension at the very end of
this script, by the way, is equivalent to the following unbound method and lambda/
bound-method map call forms:


print(list(map(IntVar.get, states)))
print(list(map(lambda var: var.get(), states)))

Though comprehensions are common in Python today, the form that seems clearest to
you may very well depend upon your shoe size...


Checkbutton, Radiobutton, and Scale | 461
Free download pdf