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

(yzsuai) #1

will really change and fetch the corresponding display’s input field value.* The variable
object get method returns as a string for StringVar, an integer for IntVar, and a floating-
point number for DoubleVar.


Of course, we’ve already seen that it’s easy to set and fetch text in Entry fields directly,
without adding extra code to use variables. So, why the bother about variable objects?
For one thing, it clears up that nasty fetch-after-destroy peril we met in the prior section.
Because StringVars live on after the Entry widgets they are tied to have been destroyed,
it’s OK to fetch input values from them long after a modal dialog has been dismissed,
as shown in Example 8-21.


Example 8-21. PP4E\Gui\Tour\entry3-modal.py


can fetch values after destroy with stringvars


from tkinter import *
from entry3 import makeform, fetch, fields


def show(variables, popup):
popup.destroy() # order doesn't matter here
fetch(variables) # variables live on after window destroyed


def ask():
popup = Toplevel() # show form in modal dialog window
vars = makeform(popup, fields)
Button(popup, text='OK', command=(lambda: show(vars, popup))).pack()
popup.grab_set()
popup.focus_set()
popup.wait_window() # wait for destroy here


root = Tk()
Button(root, text='Dialog', command=ask).pack()
root.mainloop()


This version is the same as the original (shown in Example 8-19 and Figure 8-25), but
show now destroys the pop up before inputs are fetched through StringVars in the list
created by makeform. In other words, variables are a bit more robust in some contexts
because they are not part of a real display tree. For example, they are also commonly
associated with check buttons, radio boxes, and scales in order to provide access to
current settings and link multiple widgets together. Almost coincidentally, that’s the
topic of the next section.



  • Historic anecdote: In a now-defunct tkinter release shipped with Python 1.3, you could also set and fetch
    variable values by calling them like functions, with and without an argument (e.g., var(value) and var()).
    Today, you call variable set and get methods instead. For unknown reasons, the function call form stopped
    working years ago, but you may still see it in older Python code (and in first editions of at least one O’Reilly
    Python book). If a fix made in the name of aesthetics breaks working code, is it really a fix?


456 | Chapter 8: A tkinter Tour, Part 1

Free download pdf