Skip to content

Commit 9514c71

Browse files
rosemanmiss-islington
authored andcommitted
bpo-42560: rewrite of Tkinter docs "life preserver" (pythonGH-27842)
Co-authored-by: Łukasz Langa <lukasz@langa.pl> (cherry picked from commit 08830a4) Co-authored-by: Mark Roseman <mark@markroseman.com>
1 parent 7543e7f commit 9514c71

2 files changed

Lines changed: 182 additions & 145 deletions

File tree

‎Doc/library/tkinter.rst‎

Lines changed: 176 additions & 145 deletions
Original file line numberDiff line numberDiff line change
@@ -146,210 +146,241 @@ Additional modules:
146146
Tkinter Life Preserver
147147
----------------------
148148

149-
.. sectionauthor:: Matt Conway
150-
151-
152149
This section is not designed to be an exhaustive tutorial on either Tk or
153-
Tkinter. Rather, it is intended as a stop gap, providing some introductory
154-
orientation on the system.
150+
Tkinter. For that, refer to one of the external resources noted earlier.
151+
Instead, this section provides a very quick orientation to what a Tkinter
152+
application looks like, identifies foundational Tk concepts, and
153+
explains how the Tkinter wrapper is structured.
155154

156-
Credits:
155+
The remainder of this section will help you to identify the classes,
156+
methods, and options you'll need in your Tkinter application, and where to
157+
find more detailed documentation on them, including in the official Tcl/Tk
158+
reference manual.
157159

158-
* Tk was written by John Ousterhout while at Berkeley.
159160

160-
* Tkinter was written by Steen Lumholt and Guido van Rossum.
161+
A Hello World Program
162+
^^^^^^^^^^^^^^^^^^^^^
161163

162-
* This Life Preserver was written by Matt Conway at the University of Virginia.
164+
We'll start by walking through a "Hello World" application in Tkinter. This
165+
isn't the smallest one we could write, but has enough to illustrate some
166+
key concepts you'll need to know.
163167

164-
* The HTML rendering, and some liberal editing, was produced from a FrameMaker
165-
version by Ken Manheimer.
168+
::
166169

167-
* Fredrik Lundh elaborated and revised the class interface descriptions, to get
168-
them current with Tk 4.2.
170+
from tkinter import *
171+
from tkinter import ttk
172+
root = Tk()
173+
frm = ttk.Frame(root, padding=10)
174+
frm.grid()
175+
ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
176+
ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
177+
root.mainloop()
169178

170-
* Mike Clarkson converted the documentation to LaTeX, and compiled the User
171-
Interface chapter of the reference manual.
172179

180+
After the imports, the next line creates an instance of the :class:`Tk` class,
181+
which initializes Tk and creates its associated Tcl interpreter. It also
182+
creates a toplevel window, known as the root window, which serves as the main
183+
window of the application.
173184

174-
How To Use This Section
175-
^^^^^^^^^^^^^^^^^^^^^^^
185+
The following line creates a frame widget, which in this case will contain
186+
a label and a button we'll create next. The frame is fit inside the root
187+
window.
176188

177-
This section is designed in two parts: the first half (roughly) covers
178-
background material, while the second half can be taken to the keyboard as a
179-
handy reference.
189+
The next line creates a label widget holding a static text string. The
190+
:meth:`grid` method is used to specify the relative layout (position) of the
191+
label within its containing frame widget, similar to how tables in HTML work.
180192

181-
When trying to answer questions of the form "how do I do blah", it is often best
182-
to find out how to do "blah" in straight Tk, and then convert this back into the
183-
corresponding :mod:`tkinter` call. Python programmers can often guess at the
184-
correct Python command by looking at the Tk documentation. This means that in
185-
order to use Tkinter, you will have to know a little bit about Tk. This document
186-
can't fulfill that role, so the best we can do is point you to the best
187-
documentation that exists. Here are some hints:
193+
A button widget is then created, and placed to the right of the label. When
194+
pressed, it will call the :meth:`destroy` method of the root window.
188195

189-
* The authors strongly suggest getting a copy of the Tk man pages.
190-
Specifically, the man pages in the ``manN`` directory are most useful.
191-
The ``man3`` man pages describe the C interface to the Tk library and thus
192-
are not especially helpful for script writers.
196+
Finally, the :meth:`mainloop` method puts everything on the display, and
197+
responds to user input until the program terminates.
193198

194-
* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
195-
Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
196-
the novice. The book is not exhaustive, and for many details it defers to the
197-
man pages.
198199

199-
* :file:`tkinter/__init__.py` is a last resort for most, but can be a good
200-
place to go when nothing else makes sense.
201200

201+
Important Tk Concepts
202+
^^^^^^^^^^^^^^^^^^^^^
202203

203-
A Simple Hello World Program
204-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
204+
Even this simple program illustrates the following key Tk concepts:
205205

206-
::
206+
widgets
207+
A Tkinter user interface is made up of individual *widgets*. Each widget is
208+
represented as a Python object, instantiated from classes like
209+
:class:`ttk.Frame`, :class:`ttk.Label`, and :class:`ttk.Button`.
207210

208-
import tkinter as tk
211+
widget hierarchy
212+
Widgets are arranged in a *hierarchy*. The label and button were contained
213+
within a frame, which in turn was contained within the root window. When
214+
creating each *child* widget, its *parent* widget is passed as the first
215+
argument to the widget constructor.
209216

210-
class Application(tk.Frame):
211-
def __init__(self, master=None):
212-
super().__init__(master)
213-
self.master = master
214-
self.pack()
215-
self.create_widgets()
217+
configuration options
218+
Widgets have *configuration options*, which modify their appearance and
219+
behavior, such as the text to display in a label or button. Different
220+
classes of widgets will have different sets of options.
216221

217-
def create_widgets(self):
218-
self.hi_there = tk.Button(self)
219-
self.hi_there["text"] = "Hello World\n(click me)"
220-
self.hi_there["command"] = self.say_hi
221-
self.hi_there.pack(side="top")
222+
geometry management
223+
Widgets aren't automatically added to the user interface when they are
224+
created. A *geometry manager* like ``grid`` controls where in the
225+
user interface they are placed.
222226

223-
self.quit = tk.Button(self, text="QUIT", fg="red",
224-
command=self.master.destroy)
225-
self.quit.pack(side="bottom")
227+
event loop
228+
Tkinter reacts to user input, changes from your program, and even refreshes
229+
the display only when actively running an *event loop*. If your program
230+
isn't running the event loop, your user interface won't update.
226231

227-
def say_hi(self):
228-
print("hi there, everyone!")
229232

230-
root = tk.Tk()
231-
app = Application(master=root)
232-
app.mainloop()
233+
Understanding How Tkinter Wraps Tcl/Tk
234+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
233235

236+
When your application uses Tkinter's classes and methods, internally Tkinter
237+
is assembling strings representing Tcl/Tk commands, and executing those
238+
commands in the Tcl interpreter attached to your applicaton's :class:`Tk`
239+
instance.
234240

235-
A (Very) Quick Look at Tcl/Tk
236-
-----------------------------
241+
Whether it's trying to navigate reference documentation, trying to find
242+
the right method or option, adapting some existing code, or debugging your
243+
Tkinter application, there are times that it will be useful to understand
244+
what those underlying Tcl/Tk commands look like.
237245

238-
The class hierarchy looks complicated, but in actual practice, application
239-
programmers almost always refer to the classes at the very bottom of the
240-
hierarchy.
246+
To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter
247+
script above.
241248

242-
Notes:
249+
::
243250

244-
* These classes are provided for the purposes of organizing certain functions
245-
under one namespace. They aren't meant to be instantiated independently.
251+
ttk::frame .frm -padding 10
252+
grid .frm
253+
grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0
254+
grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0
246255

247-
* The :class:`Tk` class is meant to be instantiated only once in an application.
248-
Application programmers need not instantiate one explicitly, the system creates
249-
one whenever any of the other classes are instantiated.
250256

251-
* The :class:`Widget` class is not meant to be instantiated, it is meant only
252-
for subclassing to make "real" widgets (in C++, this is called an 'abstract
253-
class').
257+
Tcl's syntax is similar to many shell languages, where the first word is the
258+
command to be executed, with arguments to that command following it, separated
259+
by spaces. Without getting into too many details, notice the following:
254260

255-
To make use of this reference material, there will be times when you will need
256-
to know how to read short passages of Tk and how to identify the various parts
257-
of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
258-
:mod:`tkinter` equivalents of what's below.)
261+
* The commands used to create widgets (like ``ttk::frame``) correspond to
262+
widget classes in Tkinter.
259263

260-
Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
261-
of tokens separated by spaces. A Tk widget is just its *class*, the *options*
262-
that help configure it, and the *actions* that make it do useful things.
264+
* Tcl widget options (like ``-text``) correspond to keyword arguments in
265+
Tkinter.
263266

264-
To make a widget in Tk, the command is always of the form::
267+
* Widgets are referred to by a *pathname* in Tcl (like ``.frm.btn``),
268+
whereas Tkinter doesn't use names but object references.
265269

266-
classCommand newPathname options
270+
* A widget's place in the widget hierarchy is encoded in its (hierarchical)
271+
pathname, which uses a ``.`` (dot) as a path separator. The pathname for
272+
the root window is just ``.`` (dot). In Tkinter, the hierarchy is defined
273+
not by pathname but by specifying the parent widget when creating each
274+
child widget.
267275

268-
*classCommand*
269-
denotes which kind of widget to make (a button, a label, a menu...)
276+
* Operations which are implemented as separate *commands* in Tcl (like
277+
``grid`` or ``destroy``) are represented as *methods* on Tkinter widget
278+
objects. As you'll see shortly, at other times Tcl uses what appear to be
279+
method calls on widget objects, which more closely mirror what would is
280+
used in Tkinter.
270281

271-
.. index:: single: . (dot); in Tkinter
272282

273-
*newPathname*
274-
is the new name for this widget. All names in Tk must be unique. To help
275-
enforce this, widgets in Tk are named with *pathnames*, just like files in a
276-
file system. The top level widget, the *root*, is called ``.`` (period) and
277-
children are delimited by more periods. For example,
278-
``.myApp.controlPanel.okButton`` might be the name of a widget.
283+
How do I...? What option does...?
284+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
279285

280-
*options*
281-
configure the widget's appearance and in some cases, its behavior. The options
282-
come in the form of a list of flags and values. Flags are preceded by a '-',
283-
like Unix shell command flags, and values are put in quotes if they are more
284-
than one word.
286+
If you're not sure how to do something in Tkinter, and you can't immediately
287+
find it in the tutorial or reference documentation you're using, there are a
288+
few strategies that can be helpful.
285289

286-
For example::
290+
First, remember that the details of how individual widgets work may vary
291+
across different versions of both Tkinter and Tcl/Tk. If you're searching
292+
documentation, make sure it corresponds to the Python and Tcl/Tk versions
293+
installed on your system.
287294

288-
button .fred -fg red -text "hi there"
289-
^ ^ \______________________/
290-
| | |
291-
class new options
292-
command widget (-opt val -opt val ...)
295+
When searching for how to use an API, it helps to know the exact name of the
296+
class, option, or method that you're using. Introspection, either in an
297+
interactive Python shell or with :func:`print`, can help you identify what
298+
you need.
293299

294-
Once created, the pathname to the widget becomes a new command. This new
295-
*widget command* is the programmer's handle for getting the new widget to
296-
perform some *action*. In C, you'd express this as someAction(fred,
297-
someOptions), in C++, you would express this as fred.someAction(someOptions),
298-
and in Tk, you say::
300+
To find out what configuration options are available on any widget, call its
301+
:meth:`configure` method, which returns a dictionary containing a variety of
302+
information about each object, including its default and current values. Use
303+
:meth:`keys` to get just the names of each option.
299304

300-
.fred someAction someOptions
305+
::
301306

302-
Note that the object name, ``.fred``, starts with a dot.
307+
btn = ttk.Button(frm, ...)
308+
print(btn.configure().keys())
303309

304-
As you'd expect, the legal values for *someAction* will depend on the widget's
305-
class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
306-
does not work if fred is a label (disabling of labels is not supported in Tk).
310+
As most widgets have many configuration options in common, it can be useful
311+
to find out which are specific to a particular widget class. Comparing the
312+
list of options to that of a simpler widget, like a frame, is one way to
313+
do that.
307314

308-
The legal values of *someOptions* is action dependent. Some actions, like
309-
``disable``, require no arguments, others, like a text-entry box's ``delete``
310-
command, would need arguments to specify what range of text to delete.
315+
::
311316

317+
print(set(btn.configure().keys()) - set(frm.configure().keys()))
312318

313-
.. _tkinter-basic-mapping:
319+
Similarly, you can find the available methods for a widget object using the
320+
standard :func:`dir` function. If you try it, you'll see there are over 200
321+
common widget methods, so again identifying those specific to a widget class
322+
is helpful.
314323

315-
Mapping Basic Tk into Tkinter
316-
-----------------------------
324+
::
317325

318-
Class commands in Tk correspond to class constructors in Tkinter. ::
326+
print(dir(btn))
327+
print(set(dir(btn)) - set(dir(frm)))
319328

320-
button .fred =====> fred = Button()
321329

322-
The master of an object is implicit in the new name given to it at creation
323-
time. In Tkinter, masters are specified explicitly. ::
330+
Navigating the Tcl/Tk Reference Manual
331+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
324332

325-
button .panel.fred =====> fred = Button(panel)
333+
As noted, the official `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
334+
reference manual (man pages) is often the most accurate description of what
335+
specific operations on widgets do. Even when you know the name of the option
336+
or method that you need, you may still have a few places to look.
326337

327-
The configuration options in Tk are given in lists of hyphened tags followed by
328-
values. In Tkinter, options are specified as keyword-arguments in the instance
329-
constructor, and keyword-args for configure calls or as instance indices, in
330-
dictionary style, for established instances. See section
331-
:ref:`tkinter-setting-options` on setting options. ::
338+
While all operations in Tkinter are implemented as method calls on widget
339+
objects, you've seen that many Tcl/Tk operations appear as commands that
340+
take a widget pathname as its first parameter, followed by optional
341+
parameters, e.g.
332342

333-
button .fred -fg red =====> fred = Button(panel, fg="red")
334-
.fred configure -fg red =====> fred["fg"] = red
335-
OR ==> fred.config(fg="red")
343+
::
336344

337-
In Tk, to perform an action on a widget, use the widget name as a command, and
338-
follow it with an action name, possibly with arguments (options). In Tkinter,
339-
you call methods on the class instance to invoke actions on the widget. The
340-
actions (methods) that a given widget can perform are listed in
341-
:file:`tkinter/__init__.py`. ::
345+
destroy .
346+
grid .frm.btn -column 0 -row 0
342347

343-
.fred invoke =====> fred.invoke()
348+
Others, however, look more like methods called on a widget object (in fact,
349+
when you create a widget in Tcl/Tk, it creates a Tcl command with the name
350+
of the widget pathname, with the first parameter to that command being the
351+
name of a method to call).
344352

345-
To give a widget to the packer (geometry manager), you call pack with optional
346-
arguments. In Tkinter, the Pack class holds all this functionality, and the
347-
various forms of the pack command are implemented as methods. All widgets in
348-
:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
349-
methods. See the :mod:`tkinter.tix` module documentation for additional
350-
information on the Form geometry manager. ::
353+
::
351354

352-
pack .fred -side left =====> fred.pack(side="left")
355+
.frm.btn invoke
356+
.frm.lbl configure -text "Goodbye"
357+
358+
359+
In the official Tcl/Tk reference documentation, you'll find most operations
360+
that look like method calls on the man page for a specific widget (e.g.,
361+
you'll find the :meth:`invoke` method on the
362+
`ttk::button <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_button.htm>`_
363+
man page), while functions that take a widget as a parameter often have
364+
their own man page (e.g.,
365+
`grid <https://www.tcl.tk/man/tcl8.6/TkCmd/grid.htm>`_).
366+
367+
You'll find many common options and methods in the
368+
`options <https://www.tcl.tk/man/tcl8.6/TkCmd/options.htm>`_ or
369+
`ttk::widget <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_widget.htm>`_ man
370+
pages, while others are found in the man page for a specific widget class.
371+
372+
You'll also find that many Tkinter methods have compound names, e.g.,
373+
:func:`winfo_x`, :func:`winfo_height`, :func:`winfo_viewable`. You'd find
374+
documentation for all of these in the
375+
`winfo <https://www.tcl.tk/man/tcl8.6/TkCmd/winfo.htm>`_ man page.
376+
377+
.. note::
378+
Somewhat confusingly, there are also methods on all Tkinter widgets
379+
that don't actually operate on the widget, but operate at a global
380+
scope, independent of any widget. Examples are methods for accessing
381+
the clipboard or the system bell. (They happen to be implemented as
382+
methods in the base :class:`Widget` class that all Tkinter widgets
383+
inherit from).
353384

354385

355386
How Tk and Tkinter are Related

‎Doc/tools/susp-ignored.csv‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,12 @@ library/tarfile,,:xz,'r:xz'
235235
library/tarfile,,:xz,'w:xz'
236236
library/time,,:mm,
237237
library/time,,:ss,
238+
library/tkinter,294,::,ttk::frame .frm -padding 10
239+
library/tkinter,294,::,"grid [ttk::label .frm.lbl -text ""Hello World!""] -column 0 -row 0"
240+
library/tkinter,294,::,"grid [ttk::button .frm.btn -text ""Quit"" -command ""destroy .""] -column 1 -row 0"
241+
library/tkinter,304,::,ttk::frame
242+
library/tkinter,402,::,ttk::button
243+
library/tkinter,410,::,ttk::widget
238244
library/tracemalloc,,:limit,"for index, stat in enumerate(top_stats[:limit], 1):"
239245
library/turtle,,::,Example::
240246
library/unittest,,:foo,"self.assertEqual(cm.output, ['INFO:foo:first message',"

0 commit comments

Comments
 (0)