@@ -207,210 +207,241 @@ Additional modules:
207
207
Tkinter Life Preserver
208
208
----------------------
209
209
210
- .. sectionauthor :: Matt Conway
210
+ This section is not designed to be an exhaustive tutorial on either Tk or
211
+ Tkinter. For that, refer to one of the external resources noted earlier.
212
+ Instead, this section provides a very quick orientation to what a Tkinter
213
+ application looks like, identifies foundational Tk concepts, and
214
+ explains how the Tkinter wrapper is structured.
211
215
216
+ The remainder of this section will help you to identify the classes,
217
+ methods, and options you'll need in your Tkinter application, and where to
218
+ find more detailed documentation on them, including in the official Tcl/Tk
219
+ reference manual.
212
220
213
- This section is not designed to be an exhaustive tutorial on either Tk or
214
- Tkinter. Rather, it is intended as a stop gap, providing some introductory
215
- orientation on the system.
216
221
217
- Credits:
222
+ A Hello World Program
223
+ ^^^^^^^^^^^^^^^^^^^^^
218
224
219
- * Tk was written by John Ousterhout while at Berkeley.
225
+ We'll start by walking through a "Hello World" application in Tkinter. This
226
+ isn't the smallest one we could write, but has enough to illustrate some
227
+ key concepts you'll need to know.
220
228
221
- * Tkinter was written by Steen Lumholt and Guido van Rossum.
229
+ ::
222
230
223
- * This Life Preserver was written by Matt Conway at the University of Virginia.
231
+ from tkinter import *
232
+ from tkinter import ttk
233
+ root = Tk()
234
+ frm = ttk.Frame(root, padding=10)
235
+ frm.grid()
236
+ ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
237
+ ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
238
+ root.mainloop()
224
239
225
- * The HTML rendering, and some liberal editing, was produced from a FrameMaker
226
- version by Ken Manheimer.
227
240
228
- * Fredrik Lundh elaborated and revised the class interface descriptions, to get
229
- them current with Tk 4.2.
241
+ After the imports, the next line creates an instance of the :class: `Tk ` class,
242
+ which initializes Tk and creates its associated Tcl interpreter. It also
243
+ creates a toplevel window, known as the root window, which serves as the main
244
+ window of the application.
230
245
231
- * Mike Clarkson converted the documentation to LaTeX, and compiled the User
232
- Interface chapter of the reference manual.
246
+ The following line creates a frame widget, which in this case will contain
247
+ a label and a button we'll create next. The frame is fit inside the root
248
+ window.
233
249
250
+ The next line creates a label widget holding a static text string. The
251
+ :meth: `grid ` method is used to specify the relative layout (position) of the
252
+ label within its containing frame widget, similar to how tables in HTML work.
234
253
235
- How To Use This Section
236
- ^^^^^^^^^^^^^^^^^^^^^^^
254
+ A button widget is then created, and placed to the right of the label. When
255
+ pressed, it will call the :meth: ` destroy ` method of the root window.
237
256
238
- This section is designed in two parts: the first half (roughly) covers
239
- background material, while the second half can be taken to the keyboard as a
240
- handy reference.
257
+ Finally, the :meth: `mainloop ` method puts everything on the display, and
258
+ responds to user input until the program terminates.
241
259
242
- When trying to answer questions of the form "how do I do blah", it is often best
243
- to find out how to do "blah" in straight Tk, and then convert this back into the
244
- corresponding :mod: `tkinter ` call. Python programmers can often guess at the
245
- correct Python command by looking at the Tk documentation. This means that in
246
- order to use Tkinter, you will have to know a little bit about Tk. This document
247
- can't fulfill that role, so the best we can do is point you to the best
248
- documentation that exists. Here are some hints:
249
260
250
- * The authors strongly suggest getting a copy of the Tk man pages.
251
- Specifically, the man pages in the ``manN `` directory are most useful.
252
- The ``man3 `` man pages describe the C interface to the Tk library and thus
253
- are not especially helpful for script writers.
254
261
255
- * Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
256
- Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
257
- the novice. The book is not exhaustive, and for many details it defers to the
258
- man pages.
262
+ Important Tk Concepts
263
+ ^^^^^^^^^^^^^^^^^^^^^
259
264
260
- * :file: `tkinter/__init__.py ` is a last resort for most, but can be a good
261
- place to go when nothing else makes sense.
265
+ Even this simple program illustrates the following key Tk concepts:
262
266
267
+ widgets
268
+ A Tkinter user interface is made up of individual *widgets *. Each widget is
269
+ represented as a Python object, instantiated from classes like
270
+ :class: `ttk.Frame `, :class: `ttk.Label `, and :class: `ttk.Button `.
263
271
264
- A Simple Hello World Program
265
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
272
+ widget hierarchy
273
+ Widgets are arranged in a *hierarchy *. The label and button were contained
274
+ within a frame, which in turn was contained within the root window. When
275
+ creating each *child * widget, its *parent * widget is passed as the first
276
+ argument to the widget constructor.
266
277
267
- ::
278
+ configuration options
279
+ Widgets have *configuration options *, which modify their appearance and
280
+ behavior, such as the text to display in a label or button. Different
281
+ classes of widgets will have different sets of options.
268
282
269
- import tkinter as tk
283
+ geometry management
284
+ Widgets aren't automatically added to the user interface when they are
285
+ created. A *geometry manager * like ``grid `` controls where in the
286
+ user interface they are placed.
270
287
271
- class Application(tk.Frame):
272
- def __init__(self, master=None):
273
- super().__init__(master)
274
- self.master = master
275
- self.pack()
276
- self.create_widgets()
288
+ event loop
289
+ Tkinter reacts to user input, changes from your program, and even refreshes
290
+ the display only when actively running an *event loop *. If your program
291
+ isn't running the event loop, your user interface won't update.
277
292
278
- def create_widgets(self):
279
- self.hi_there = tk.Button(self)
280
- self.hi_there["text"] = "Hello World\n(click me)"
281
- self.hi_there["command"] = self.say_hi
282
- self.hi_there.pack(side="top")
283
293
284
- self.quit = tk.Button(self, text="QUIT", fg="red",
285
- command=self.master.destroy)
286
- self.quit.pack(side="bottom")
294
+ Understanding How Tkinter Wraps Tcl/Tk
295
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
287
296
288
- def say_hi(self):
289
- print("hi there, everyone!")
297
+ When your application uses Tkinter's classes and methods, internally Tkinter
298
+ is assembling strings representing Tcl/Tk commands, and executing those
299
+ commands in the Tcl interpreter attached to your applicaton's :class: `Tk `
300
+ instance.
290
301
291
- root = tk.Tk()
292
- app = Application(master=root)
293
- app.mainloop()
302
+ Whether it's trying to navigate reference documentation, trying to find
303
+ the right method or option, adapting some existing code, or debugging your
304
+ Tkinter application, there are times that it will be useful to understand
305
+ what those underlying Tcl/Tk commands look like.
294
306
307
+ To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter
308
+ script above.
295
309
296
- A (Very) Quick Look at Tcl/Tk
297
- -----------------------------
310
+ ::
298
311
299
- The class hierarchy looks complicated, but in actual practice, application
300
- programmers almost always refer to the classes at the very bottom of the
301
- hierarchy.
312
+ ttk::frame .frm -padding 10
313
+ grid .frm
314
+ grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0
315
+ grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0
302
316
303
- Notes:
304
317
305
- * These classes are provided for the purposes of organizing certain functions
306
- under one namespace. They aren't meant to be instantiated independently.
318
+ Tcl's syntax is similar to many shell languages, where the first word is the
319
+ command to be executed, with arguments to that command following it, separated
320
+ by spaces. Without getting into too many details, notice the following:
307
321
308
- * The :class: `Tk ` class is meant to be instantiated only once in an application.
309
- Application programmers need not instantiate one explicitly, the system creates
310
- one whenever any of the other classes are instantiated.
322
+ * The commands used to create widgets (like ``ttk::frame ``) correspond to
323
+ widget classes in Tkinter.
311
324
312
- * The :class: `Widget ` class is not meant to be instantiated, it is meant only
313
- for subclassing to make "real" widgets (in C++, this is called an 'abstract
314
- class').
325
+ * Tcl widget options (like ``-text ``) correspond to keyword arguments in
326
+ Tkinter.
315
327
316
- To make use of this reference material, there will be times when you will need
317
- to know how to read short passages of Tk and how to identify the various parts
318
- of a Tk command. (See section :ref: `tkinter-basic-mapping ` for the
319
- :mod: `tkinter ` equivalents of what's below.)
328
+ * Widgets are referred to by a *pathname * in Tcl (like ``.frm.btn ``),
329
+ whereas Tkinter doesn't use names but object references.
320
330
321
- Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
322
- of tokens separated by spaces. A Tk widget is just its *class *, the *options *
323
- that help configure it, and the *actions * that make it do useful things.
331
+ * A widget's place in the widget hierarchy is encoded in its (hierarchical)
332
+ pathname, which uses a ``. `` (dot) as a path separator. The pathname for
333
+ the root window is just ``. `` (dot). In Tkinter, the hierarchy is defined
334
+ not by pathname but by specifying the parent widget when creating each
335
+ child widget.
324
336
325
- To make a widget in Tk, the command is always of the form::
337
+ * Operations which are implemented as separate *commands * in Tcl (like
338
+ ``grid `` or ``destroy ``) are represented as *methods * on Tkinter widget
339
+ objects. As you'll see shortly, at other times Tcl uses what appear to be
340
+ method calls on widget objects, which more closely mirror what would is
341
+ used in Tkinter.
326
342
327
- classCommand newPathname options
328
343
329
- * classCommand *
330
- denotes which kind of widget to make (a button, a label, a menu...)
344
+ How do I...? What option does...?
345
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
331
346
332
- .. index :: single: . (dot); in Tkinter
347
+ If you're not sure how to do something in Tkinter, and you can't immediately
348
+ find it in the tutorial or reference documentation you're using, there are a
349
+ few strategies that can be helpful.
333
350
334
- *newPathname *
335
- is the new name for this widget. All names in Tk must be unique. To help
336
- enforce this, widgets in Tk are named with *pathnames *, just like files in a
337
- file system. The top level widget, the *root *, is called ``. `` (period) and
338
- children are delimited by more periods. For example,
339
- ``.myApp.controlPanel.okButton `` might be the name of a widget.
351
+ First, remember that the details of how individual widgets work may vary
352
+ across different versions of both Tkinter and Tcl/Tk. If you're searching
353
+ documentation, make sure it corresponds to the Python and Tcl/Tk versions
354
+ installed on your system.
340
355
341
- *options *
342
- configure the widget's appearance and in some cases, its behavior. The options
343
- come in the form of a list of flags and values. Flags are preceded by a '-',
344
- like Unix shell command flags, and values are put in quotes if they are more
345
- than one word.
356
+ When searching for how to use an API, it helps to know the exact name of the
357
+ class, option, or method that you're using. Introspection, either in an
358
+ interactive Python shell or with :func: `print `, can help you identify what
359
+ you need.
346
360
347
- For example::
361
+ To find out what configuration options are available on any widget, call its
362
+ :meth: `configure ` method, which returns a dictionary containing a variety of
363
+ information about each object, including its default and current values. Use
364
+ :meth: `keys ` to get just the names of each option.
348
365
349
- button .fred -fg red -text "hi there"
350
- ^ ^ \______________________/
351
- | | |
352
- class new options
353
- command widget (-opt val -opt val ...)
366
+ ::
354
367
355
- Once created, the pathname to the widget becomes a new command. This new
356
- *widget command * is the programmer's handle for getting the new widget to
357
- perform some *action *. In C, you'd express this as someAction(fred,
358
- someOptions), in C++, you would express this as fred.someAction(someOptions),
359
- and in Tk, you say::
368
+ btn = ttk.Button(frm, ...)
369
+ print(btn.configure().keys())
360
370
361
- .fred someAction someOptions
371
+ As most widgets have many configuration options in common, it can be useful
372
+ to find out which are specific to a particular widget class. Comparing the
373
+ list of options to that of a simpler widget, like a frame, is one way to
374
+ do that.
362
375
363
- Note that the object name, `` .fred ``, starts with a dot.
376
+ ::
364
377
365
- As you'd expect, the legal values for *someAction * will depend on the widget's
366
- class: ``.fred disable `` works if fred is a button (fred gets greyed out), but
367
- does not work if fred is a label (disabling of labels is not supported in Tk).
378
+ print(set(btn.configure().keys()) - set(frm.configure().keys()))
368
379
369
- The legal values of *someOptions * is action dependent. Some actions, like
370
- ``disable ``, require no arguments, others, like a text-entry box's ``delete ``
371
- command, would need arguments to specify what range of text to delete.
380
+ Similarly, you can find the available methods for a widget object using the
381
+ standard :func: `dir ` function. If you try it, you'll see there are over 200
382
+ common widget methods, so again identifying those specific to a widget class
383
+ is helpful.
372
384
385
+ ::
386
+
387
+ print(dir(btn))
388
+ print(set(dir(btn)) - set(dir(frm)))
373
389
374
- .. _tkinter-basic-mapping :
375
390
376
- Mapping Basic Tk into Tkinter
377
- -----------------------------
391
+ Navigating the Tcl/ Tk Reference Manual
392
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
378
393
379
- Class commands in Tk correspond to class constructors in Tkinter. ::
394
+ As noted, the official `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm >`_
395
+ reference manual (man pages) is often the most accurate description of what
396
+ specific operations on widgets do. Even when you know the name of the option
397
+ or method that you need, you may still have a few places to look.
380
398
381
- button .fred =====> fred = Button()
399
+ While all operations in Tkinter are implemented as method calls on widget
400
+ objects, you've seen that many Tcl/Tk operations appear as commands that
401
+ take a widget pathname as its first parameter, followed by optional
402
+ parameters, e.g.
382
403
383
- The master of an object is implicit in the new name given to it at creation
384
- time. In Tkinter, masters are specified explicitly. ::
404
+ ::
385
405
386
- button .panel.fred =====> fred = Button(panel)
406
+ destroy .
407
+ grid .frm.btn -column 0 -row 0
387
408
388
- The configuration options in Tk are given in lists of hyphened tags followed by
389
- values. In Tkinter, options are specified as keyword-arguments in the instance
390
- constructor, and keyword-args for configure calls or as instance indices, in
391
- dictionary style, for established instances. See section
392
- :ref: `tkinter-setting-options ` on setting options. ::
409
+ Others, however, look more like methods called on a widget object (in fact,
410
+ when you create a widget in Tcl/Tk, it creates a Tcl command with the name
411
+ of the widget pathname, with the first parameter to that command being the
412
+ name of a method to call).
393
413
394
- button .fred -fg red =====> fred = Button(panel, fg="red")
395
- .fred configure -fg red =====> fred["fg"] = red
396
- OR ==> fred.config(fg="red")
414
+ ::
397
415
398
- In Tk, to perform an action on a widget, use the widget name as a command, and
399
- follow it with an action name, possibly with arguments (options). In Tkinter,
400
- you call methods on the class instance to invoke actions on the widget. The
401
- actions (methods) that a given widget can perform are listed in
402
- :file: `tkinter/__init__.py `. ::
416
+ .frm.btn invoke
417
+ .frm.lbl configure -text "Goodbye"
403
418
404
- .fred invoke =====> fred.invoke()
405
419
406
- To give a widget to the packer (geometry manager), you call pack with optional
407
- arguments. In Tkinter, the Pack class holds all this functionality, and the
408
- various forms of the pack command are implemented as methods. All widgets in
409
- :mod: `tkinter ` are subclassed from the Packer, and so inherit all the packing
410
- methods. See the :mod: `tkinter.tix ` module documentation for additional
411
- information on the Form geometry manager. ::
420
+ In the official Tcl/Tk reference documentation, you'll find most operations
421
+ that look like method calls on the man page for a specific widget (e.g.,
422
+ you'll find the :meth: `invoke ` method on the
423
+ `ttk::button <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_button.htm >`_
424
+ man page), while functions that take a widget as a parameter often have
425
+ their own man page (e.g.,
426
+ `grid <https://www.tcl.tk/man/tcl8.6/TkCmd/grid.htm >`_).
412
427
413
- pack .fred -side left =====> fred.pack(side="left")
428
+ You'll find many common options and methods in the
429
+ `options <https://www.tcl.tk/man/tcl8.6/TkCmd/options.htm >`_ or
430
+ `ttk::widget <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_widget.htm >`_ man
431
+ pages, while others are found in the man page for a specific widget class.
432
+
433
+ You'll also find that many Tkinter methods have compound names, e.g.,
434
+ :func: `winfo_x `, :func: `winfo_height `, :func: `winfo_viewable `. You'd find
435
+ documentation for all of these in the
436
+ `winfo <https://www.tcl.tk/man/tcl8.6/TkCmd/winfo.htm >`_ man page.
437
+
438
+ .. note ::
439
+ Somewhat confusingly, there are also methods on all Tkinter widgets
440
+ that don't actually operate on the widget, but operate at a global
441
+ scope, independent of any widget. Examples are methods for accessing
442
+ the clipboard or the system bell. (They happen to be implemented as
443
+ methods in the base :class: `Widget ` class that all Tkinter widgets
444
+ inherit from).
414
445
415
446
416
447
Threading model
0 commit comments