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

(yzsuai) #1

Linked variables (next chapter)
Variables associated with widgets are tkinter class objects with methods.


In Python, widget creation commands (e.g., button) are Python class names that start
with an uppercase letter (e.g., Button), two-word widget operations (e.g., add command)
become a single method name with an underscore (e.g., add_command), and the “con-
figure” method can be abbreviated as “config,” as in Tcl. In Chapter 8, we will also see
that tkinter “variables” associated with widgets take the form of class instance objects
(e.g., StringVar, IntVar) with get and set methods, not simple Python or Tcl variable
names. Table 7-2 shows some of the primary language mappings in more concrete
terms.


Table 7-2. Tk-to-tkinter mappings


Operation Tcl/Tk Python/tkinter
Creation Frame .panel panel = Frame()
Masters button .panel.quit quit = Button(panel)
Options button .panel.go -fg black go = Button(panel, fg='black')
Configure .panel.go config -bg red go.config(bg='red') go['bg'] = ‘red’
Actions .popup invoke popup.invoke()
Packing pack .panel -side left -fill x panel.pack(side=LEFT, fill=X)

Some of these differences are more than just syntactic, of course. For instance, Python
builds an internal widget object tree based on parent arguments passed to widget con-
structors, without ever requiring concatenated widget pathname strings. Once you’ve
made a widget object, you can use it directly by object reference. Tcl coders can hide
some dotted pathnames by manually storing them in variables, but that’s not quite the
same as Python’s purely object-based model.


Once you’ve written a few Python/tkinter scripts, though, the coding distinctions in
the Python object world will probably seem trivial. At the same time, Python’s support
for object-oriented techniques adds an entirely new component to Tk development;
you get the same widgets, plus Python’s support for code structure and reuse.


Python/tkinter for Tcl/Tk Converts | 413
Free download pdf