Debian Codegraph @

Doc/library/tkinter.rst

raw
1 :mod:`!tkinter` --- Python interface to Tcl/Tk
2 ==============================================
3
4 .. module:: tkinter
5 :synopsis: Interface to Tcl/Tk for graphical user interfaces
6
7 .. moduleauthor:: Guido van Rossum <[email protected]>
8
9 **Source code:** :source:`Lib/tkinter/__init__.py`
10
11 --------------
12
13 The :mod:`!tkinter` package ("Tk interface") is the standard Python interface to
14 the Tcl/Tk GUI toolkit. Both Tk and :mod:`!tkinter` are available on most Unix
15 platforms, including macOS, as well as on Windows systems.
16
17 Running ``python -m tkinter`` from the command line should open a window
18 demonstrating a simple Tk interface, letting you know that :mod:`!tkinter` is
19 properly installed on your system, and also showing what version of Tcl/Tk is
20 installed, so you can read the Tcl/Tk documentation specific to that version.
21
22 Tkinter supports a range of Tcl/Tk versions, built either with or
23 without thread support. The official Python binary release bundles Tcl/Tk 8.6
24 threaded. See the source code for the :mod:`_tkinter` module
25 for more information about supported versions.
26
27 Tkinter is not a thin wrapper, but adds a fair amount of its own logic to
28 make the experience more pythonic. This documentation will concentrate on these
29 additions and changes, and refer to the official Tcl/Tk documentation for
30 details that are unchanged.
31
32 .. note::
33
34 Tcl/Tk 8.5 (2007) introduced a modern set of themed user interface components
35 along with a new API to use them. Both old and new APIs are still available.
36 Most documentation you will find online still uses the old API and
37 can be woefully outdated.
38
39 .. include:: ../includes/optional-module.rst
40
41 .. seealso::
42
43 * `TkDocs <https://tkdocs.com/>`_
44 Extensive tutorial on creating user interfaces with Tkinter. Explains key concepts,
45 and illustrates recommended approaches using the modern API.
46
47 * `Tkinter 8.5 reference: a GUI for Python <https://www.tkdocs.com/shipman/>`_
48 Reference documentation for Tkinter 8.5 detailing available classes, methods, and options.
49
50 Tcl/Tk Resources:
51
52 * `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
53 Comprehensive reference to each of the underlying Tcl/Tk commands used by Tkinter.
54
55 * `Tcl/Tk Home Page <https://www.tcl.tk>`_
56 Additional documentation, and links to Tcl/Tk core development.
57
58 Books:
59
60 * `Modern Tkinter for Busy Python Developers <https://tkdocs.com/book.html>`_
61 By Mark Roseman. (ISBN 978-1999149567)
62
63 * `Python GUI programming with Tkinter <https://www.packtpub.com/en-us/product/python-gui-programming-with-tkinter-9781788835886>`_
64 By Alan D. Moore. (ISBN 978-1788835886)
65
66 * `Programming Python <https://learning-python.com/about-pp4e.html>`_
67 By Mark Lutz; has excellent coverage of Tkinter. (ISBN 978-0596158101)
68
69 * `Tcl and the Tk Toolkit (2nd edition) <https://www.amazon.com/exec/obidos/ASIN/032133633X>`_
70 By John Ousterhout, inventor of Tcl/Tk, and Ken Jones; does not cover Tkinter. (ISBN 978-0321336330)
71
72
73 Architecture
74 ------------
75
76 Tcl/Tk is not a single library but rather consists of a few distinct
77 modules, each with separate functionality and its own official
78 documentation. Python's binary releases also ship an add-on module
79 together with it.
80
81 Tcl
82 Tcl is a dynamic interpreted programming language, just like Python. Though
83 it can be used on its own as a general-purpose programming language, it is
84 most commonly embedded into C applications as a scripting engine or an
85 interface to the Tk toolkit. The Tcl library has a C interface to
86 create and manage one or more instances of a Tcl interpreter, run Tcl
87 commands and scripts in those instances, and add custom commands
88 implemented in either Tcl or C. Each interpreter has an event queue,
89 and there are facilities to send events to it and process them.
90 Unlike Python, Tcl's execution model is designed around cooperative
91 multitasking, and Tkinter bridges this difference
92 (see `Threading model`_ for details).
93
94 Tk
95 Tk is a `Tcl package <https://wiki.tcl-lang.org/37432>`_ implemented in C
96 that adds custom commands to create and manipulate GUI widgets. Each
97 :class:`Tk` object embeds its own Tcl interpreter instance with Tk loaded into
98 it. Tk's widgets are very customizable, though at the cost of a dated appearance.
99 Tk uses Tcl's event queue to generate and process GUI events.
100
101 Ttk
102 Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better
103 appearance on different platforms than many of the classic Tk widgets.
104 Ttk is distributed as part of Tk, starting with Tk version 8.5. Python
105 bindings are provided in a separate module, :mod:`tkinter.ttk`.
106
107 Internally, Tk and Ttk use facilities of the underlying operating system,
108 i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.
109
110 When your Python application uses a class in Tkinter, e.g., to create a widget,
111 the :mod:`!tkinter` module first assembles a Tcl/Tk command string. It passes that
112 Tcl command string to an internal :mod:`_tkinter` binary module, which then
113 calls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the
114 Tk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI.
115
116
117 Tkinter Modules
118 ---------------
119
120 Support for Tkinter is spread across several modules. Most applications will need the
121 main :mod:`!tkinter` module, as well as the :mod:`tkinter.ttk` module, which provides
122 the modern themed widget set and API::
123
124
125 from tkinter import *
126 from tkinter import ttk
127
128
129 .. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=True, sync=False, use=None)
130
131 Construct a toplevel Tk widget, which is usually the main window of an
132 application, and initialize a Tcl interpreter for this widget. Each
133 instance has its own associated Tcl interpreter.
134
135 The :class:`Tk` class is typically instantiated using all default values.
136 However, the following keyword arguments are currently recognized:
137
138 *screenName*
139 When given (as a string), sets the :envvar:`DISPLAY` environment
140 variable. (X11 only)
141 *baseName*
142 Name of the profile file. By default, *baseName* is derived from the
143 program name (``sys.argv[0]``).
144 *className*
145 Name of the widget class. Used as a profile file and also as the name
146 with which Tcl is invoked (*argv0* in *interp*).
147 *useTk*
148 If ``True``, initialize the Tk subsystem. The :func:`tkinter.Tcl() <Tcl>`
149 function sets this to ``False``.
150 *sync*
151 If ``True``, execute all X server commands synchronously, so that errors
152 are reported immediately. Can be used for debugging. (X11 only)
153 *use*
154 Specifies the *id* of the window in which to embed the application,
155 instead of it being created as an independent toplevel window. *id* must
156 be specified in the same way as the value for the -use option for
157 toplevel widgets (that is, it has a form like that returned by
158 :meth:`winfo_id`).
159
160 Note that on some platforms this will only work correctly if *id* refers
161 to a Tk frame or toplevel that has its -container option enabled.
162
163 :class:`Tk` reads and interprets profile files, named
164 :file:`.{className}.tcl` and :file:`.{baseName}.tcl`, into the Tcl
165 interpreter and calls :func:`exec` on the contents of
166 :file:`.{className}.py` and :file:`.{baseName}.py`. The path for the
167 profile files is the :envvar:`HOME` environment variable or, if that
168 isn't defined, then :data:`os.curdir`.
169
170 .. attribute:: tk
171
172 The Tk application object created by instantiating :class:`Tk`. This
173 provides access to the Tcl interpreter. Each widget that is attached
174 the same instance of :class:`Tk` has the same value for its :attr:`tk`
175 attribute.
176
177 .. attribute:: master
178
179 The widget object that contains this widget. For :class:`Tk`, the
180 :attr:`!master` is :const:`None` because it is the main window. The terms
181 *master* and *parent* are similar and sometimes used interchangeably
182 as argument names; however, calling :meth:`winfo_parent` returns a
183 string of the widget name whereas :attr:`!master` returns the object.
184 *parent*/*child* reflects the tree-like relationship while
185 *master* (or *container*)/*content* reflects the container structure.
186
187 .. attribute:: children
188
189 The immediate descendants of this widget as a :class:`dict` with the
190 child widget names as the keys and the child instance objects as the
191 values.
192
193
194 .. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=False)
195
196 The :func:`Tcl` function is a factory function which creates an object much like
197 that created by the :class:`Tk` class, except that it does not initialize the Tk
198 subsystem. This is most often useful when driving the Tcl interpreter in an
199 environment where one doesn't want to create extraneous toplevel windows, or
200 where one cannot (such as Unix/Linux systems without an X server). An object
201 created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
202 subsystem initialized) by calling its :meth:`loadtk` method.
203
204
205 The modules that provide Tk support include:
206
207 :mod:`!tkinter`
208 Main Tkinter module.
209
210 :mod:`tkinter.colorchooser`
211 Dialog to let the user choose a color.
212
213 :mod:`tkinter.commondialog`
214 Base class for the dialogs defined in the other modules listed here.
215
216 :mod:`tkinter.filedialog`
217 Common dialogs to allow the user to specify a file to open or save.
218
219 :mod:`tkinter.font`
220 Utilities to help work with fonts.
221
222 :mod:`tkinter.messagebox`
223 Access to standard Tk dialog boxes.
224
225 :mod:`tkinter.scrolledtext`
226 Text widget with a vertical scroll bar built in.
227
228 :mod:`tkinter.simpledialog`
229 Basic dialogs and convenience functions.
230
231 :mod:`tkinter.ttk`
232 Themed widget set introduced in Tk 8.5, providing modern alternatives
233 for many of the classic widgets in the main :mod:`!tkinter` module.
234
235 Additional modules:
236
237 .. module:: _tkinter
238 :synopsis: A binary module that contains the low-level interface to Tcl/Tk.
239
240 :mod:`_tkinter`
241 A binary module that contains the low-level interface to Tcl/Tk.
242 It is automatically imported by the main :mod:`!tkinter` module,
243 and should never be used directly by application programmers.
244 It is usually a shared library (or DLL), but might in some cases be
245 statically linked with the Python interpreter.
246
247 :mod:`idlelib`
248 Python's Integrated Development and Learning Environment (IDLE). Based
249 on :mod:`!tkinter`.
250
251 :mod:`tkinter.constants`
252 Symbolic constants that can be used in place of strings when passing
253 various parameters to Tkinter calls. Automatically imported by the
254 main :mod:`!tkinter` module.
255
256 :mod:`tkinter.dnd`
257 (experimental) Drag-and-drop support for :mod:`!tkinter`. This will
258 become deprecated when it is replaced with the Tk DND.
259
260 :mod:`turtle`
261 Turtle graphics in a Tk window.
262
263
264 Tkinter Life Preserver
265 ----------------------
266
267 This section is not designed to be an exhaustive tutorial on either Tk or
268 Tkinter. For that, refer to one of the external resources noted earlier.
269 Instead, this section provides a very quick orientation to what a Tkinter
270 application looks like, identifies foundational Tk concepts, and
271 explains how the Tkinter wrapper is structured.
272
273 The remainder of this section will help you to identify the classes,
274 methods, and options you'll need in your Tkinter application, and where to
275 find more detailed documentation on them, including in the official Tcl/Tk
276 reference manual.
277
278
279 A Hello World Program
280 ^^^^^^^^^^^^^^^^^^^^^
281
282 We'll start by walking through a "Hello World" application in Tkinter. This
283 isn't the smallest one we could write, but has enough to illustrate some
284 key concepts you'll need to know.
285
286 ::
287
288 from tkinter import *
289 from tkinter import ttk
290 root = Tk()
291 frm = ttk.Frame(root, padding=10)
292 frm.grid()
293 ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
294 ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
295 root.mainloop()
296
297
298 After the imports, the next line creates an instance of the :class:`Tk` class,
299 which initializes Tk and creates its associated Tcl interpreter. It also
300 creates a toplevel window, known as the root window, which serves as the main
301 window of the application.
302
303 The following line creates a frame widget, which in this case will contain
304 a label and a button we'll create next. The frame is fit inside the root
305 window.
306
307 The next line creates a label widget holding a static text string. The
308 :meth:`grid` method is used to specify the relative layout (position) of the
309 label within its containing frame widget, similar to how tables in HTML work.
310
311 A button widget is then created, and placed to the right of the label. When
312 pressed, it will call the :meth:`destroy` method of the root window.
313
314 Finally, the :meth:`mainloop` method puts everything on the display, and
315 responds to user input until the program terminates.
316
317
318
319 Important Tk Concepts
320 ^^^^^^^^^^^^^^^^^^^^^
321
322 Even this simple program illustrates the following key Tk concepts:
323
324 widgets
325 A Tkinter user interface is made up of individual *widgets*. Each widget is
326 represented as a Python object, instantiated from classes like
327 :class:`ttk.Frame`, :class:`ttk.Label`, and :class:`ttk.Button`.
328
329 widget hierarchy
330 Widgets are arranged in a *hierarchy*. The label and button were contained
331 within a frame, which in turn was contained within the root window. When
332 creating each *child* widget, its *parent* widget is passed as the first
333 argument to the widget constructor.
334
335 configuration options
336 Widgets have *configuration options*, which modify their appearance and
337 behavior, such as the text to display in a label or button. Different
338 classes of widgets will have different sets of options.
339
340 geometry management
341 Widgets aren't automatically added to the user interface when they are
342 created. A *geometry manager* like ``grid`` controls where in the
343 user interface they are placed.
344
345 event loop
346 Tkinter reacts to user input, changes from your program, and even refreshes
347 the display only when actively running an *event loop*. If your program
348 isn't running the event loop, your user interface won't update.
349
350
351 Understanding How Tkinter Wraps Tcl/Tk
352 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
353
354 When your application uses Tkinter's classes and methods, internally Tkinter
355 is assembling strings representing Tcl/Tk commands, and executing those
356 commands in the Tcl interpreter attached to your application's :class:`Tk`
357 instance.
358
359 Whether it's trying to navigate reference documentation, trying to find
360 the right method or option, adapting some existing code, or debugging your
361 Tkinter application, there are times that it will be useful to understand
362 what those underlying Tcl/Tk commands look like.
363
364 To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter
365 script above.
366
367 ::
368
369 ttk::frame .frm -padding 10
370 grid .frm
371 grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0
372 grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0
373
374
375 Tcl's syntax is similar to many shell languages, where the first word is the
376 command to be executed, with arguments to that command following it, separated
377 by spaces. Without getting into too many details, notice the following:
378
379 * The commands used to create widgets (like ``ttk::frame``) correspond to
380 widget classes in Tkinter.
381
382 * Tcl widget options (like ``-text``) correspond to keyword arguments in
383 Tkinter.
384
385 * Widgets are referred to by a *pathname* in Tcl (like ``.frm.btn``),
386 whereas Tkinter doesn't use names but object references.
387
388 * A widget's place in the widget hierarchy is encoded in its (hierarchical)
389 pathname, which uses a ``.`` (dot) as a path separator. The pathname for
390 the root window is just ``.`` (dot). In Tkinter, the hierarchy is defined
391 not by pathname but by specifying the parent widget when creating each
392 child widget.
393
394 * Operations which are implemented as separate *commands* in Tcl (like
395 ``grid`` or ``destroy``) are represented as *methods* on Tkinter widget
396 objects. As you'll see shortly, at other times Tcl uses what appear to be
397 method calls on widget objects, which more closely mirror what is
398 used in Tkinter.
399
400
401 How do I...? What option does...?
402 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
403
404 If you're not sure how to do something in Tkinter, and you can't immediately
405 find it in the tutorial or reference documentation you're using, there are a
406 few strategies that can be helpful.
407
408 First, remember that the details of how individual widgets work may vary
409 across different versions of both Tkinter and Tcl/Tk. If you're searching
410 documentation, make sure it corresponds to the Python and Tcl/Tk versions
411 installed on your system.
412
413 When searching for how to use an API, it helps to know the exact name of the
414 class, option, or method that you're using. Introspection, either in an
415 interactive Python shell or with :func:`print`, can help you identify what
416 you need.
417
418 To find out what configuration options are available on any widget, call its
419 :meth:`configure` method, which returns a dictionary containing a variety of
420 information about each object, including its default and current values. Use
421 :meth:`keys` to get just the names of each option.
422
423 ::
424
425 btn = ttk.Button(frm, ...)
426 print(btn.configure().keys())
427
428 As most widgets have many configuration options in common, it can be useful
429 to find out which are specific to a particular widget class. Comparing the
430 list of options to that of a simpler widget, like a frame, is one way to
431 do that.
432
433 ::
434
435 print(set(btn.configure().keys()) - set(frm.configure().keys()))
436
437 Similarly, you can find the available methods for a widget object using the
438 standard :func:`dir` function. If you try it, you'll see there are over 200
439 common widget methods, so again identifying those specific to a widget class
440 is helpful.
441
442 ::
443
444 print(dir(btn))
445 print(set(dir(btn)) - set(dir(frm)))
446
447
448 Navigating the Tcl/Tk Reference Manual
449 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
450
451 As noted, the official `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
452 reference manual (man pages) is often the most accurate description of what
453 specific operations on widgets do. Even when you know the name of the option
454 or method that you need, you may still have a few places to look.
455
456 While all operations in Tkinter are implemented as method calls on widget
457 objects, you've seen that many Tcl/Tk operations appear as commands that
458 take a widget pathname as its first parameter, followed by optional
459 parameters, e.g.
460
461 ::
462
463 destroy .
464 grid .frm.btn -column 0 -row 0
465
466 Others, however, look more like methods called on a widget object (in fact,
467 when you create a widget in Tcl/Tk, it creates a Tcl command with the name
468 of the widget pathname, with the first parameter to that command being the
469 name of a method to call).
470
471 ::
472
473 .frm.btn invoke
474 .frm.lbl configure -text "Goodbye"
475
476
477 In the official Tcl/Tk reference documentation, you'll find most operations
478 that look like method calls on the man page for a specific widget (e.g.,
479 you'll find the :meth:`invoke` method on the
480 `ttk::button <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_button.htm>`_
481 man page), while functions that take a widget as a parameter often have
482 their own man page (e.g.,
483 `grid <https://www.tcl.tk/man/tcl8.6/TkCmd/grid.htm>`_).
484
485 You'll find many common options and methods in the
486 `options <https://www.tcl.tk/man/tcl8.6/TkCmd/options.htm>`_ or
487 `ttk::widget <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_widget.htm>`_ man
488 pages, while others are found in the man page for a specific widget class.
489
490 You'll also find that many Tkinter methods have compound names, e.g.,
491 :func:`winfo_x`, :func:`winfo_height`, :func:`winfo_viewable`. You'd find
492 documentation for all of these in the
493 `winfo <https://www.tcl.tk/man/tcl8.6/TkCmd/winfo.htm>`_ man page.
494
495 .. note::
496 Somewhat confusingly, there are also methods on all Tkinter widgets
497 that don't actually operate on the widget, but operate at a global
498 scope, independent of any widget. Examples are methods for accessing
499 the clipboard or the system bell. (They happen to be implemented as
500 methods in the base :class:`Widget` class that all Tkinter widgets
501 inherit from).
502
503
504 Threading model
505 ---------------
506
507 Python and Tcl/Tk have very different threading models, which :mod:`!tkinter`
508 tries to bridge. If you use threads, you may need to be aware of this.
509
510 A Python interpreter may have many threads associated with it. In Tcl, multiple
511 threads can be created, but each thread has a separate Tcl interpreter instance
512 associated with it. Threads can also create more than one interpreter instance,
513 though each interpreter instance can be used only by the one thread that created it.
514
515 Each :class:`Tk` object created by :mod:`!tkinter` contains a Tcl interpreter.
516 It also keeps track of which thread created that interpreter. Calls to
517 :mod:`!tkinter` can be made from any Python thread. Internally, if a call comes
518 from a thread other than the one that created the :class:`Tk` object, an event
519 is posted to the interpreter's event queue, and when executed, the result is
520 returned to the calling Python thread.
521
522 Tcl/Tk applications are normally event-driven, meaning that after initialization,
523 the interpreter runs an event loop (i.e. :func:`Tk.mainloop`) and responds to events.
524 Because it is single-threaded, event handlers must respond quickly, otherwise they
525 will block other events from being processed. To avoid this, any long-running
526 computations should not run in an event handler, but are either broken into smaller
527 pieces using timers, or run in another thread. This is different from many GUI
528 toolkits where the GUI runs in a completely separate thread from all application
529 code including event handlers.
530
531 If the Tcl interpreter is not running the event loop and processing events, any
532 :mod:`!tkinter` calls made from threads other than the one running the Tcl
533 interpreter will fail.
534
535 A number of special cases exist:
536
537 * Tcl/Tk libraries can be built so they are not thread-aware. In this case,
538 :mod:`!tkinter` calls the library from the originating Python thread, even
539 if this is different than the thread that created the Tcl interpreter. A global
540 lock ensures only one call occurs at a time.
541
542 * While :mod:`!tkinter` allows you to create more than one instance of a :class:`Tk`
543 object (with its own interpreter), all interpreters that are part of the same
544 thread share a common event queue, which gets ugly fast. In practice, don't create
545 more than one instance of :class:`Tk` at a time. Otherwise, it's best to create
546 them in separate threads and ensure you're running a thread-aware Tcl/Tk build.
547
548 * Blocking event handlers are not the only way to prevent the Tcl interpreter from
549 reentering the event loop. It is even possible to run multiple nested event loops
550 or abandon the event loop entirely. If you're doing anything tricky when it comes
551 to events or threads, be aware of these possibilities.
552
553 * There are a few select :mod:`!tkinter` functions that presently work only when
554 called from the thread that created the Tcl interpreter.
555
556
557 Handy Reference
558 ---------------
559
560
561 .. _tkinter-setting-options:
562
563 Setting Options
564 ^^^^^^^^^^^^^^^
565
566 Options control things like the color and border width of a widget. Options can
567 be set in three ways:
568
569 At object creation time, using keyword arguments
570 ::
571
572 fred = Button(self, fg="red", bg="blue")
573
574 After object creation, treating the option name like a dictionary index
575 ::
576
577 fred["fg"] = "red"
578 fred["bg"] = "blue"
579
580 Use the config() method to update multiple attrs subsequent to object creation
581 ::
582
583 fred.config(fg="red", bg="blue")
584
585 For a complete explanation of a given option and its behavior, see the Tk man
586 pages for the widget in question.
587
588 Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
589 for each widget. The former is a list of options that are common to many
590 widgets, the latter are the options that are idiosyncratic to that particular
591 widget. The Standard Options are documented on the :manpage:`options(3)` man
592 page.
593
594 No distinction between standard and widget-specific options is made in this
595 document. Some options don't apply to some kinds of widgets. Whether a given
596 widget responds to a particular option depends on the class of the widget;
597 buttons have a ``command`` option, labels do not.
598
599 The options supported by a given widget are listed in that widget's man page, or
600 can be queried at runtime by calling the :meth:`config` method without
601 arguments, or by calling the :meth:`keys` method on that widget. The return
602 value of these calls is a dictionary whose key is the name of the option as a
603 string (for example, ``'relief'``) and whose values are 5-tuples.
604
605 Some options, like ``bg`` are synonyms for common options with long names
606 (``bg`` is shorthand for "background"). Passing the ``config()`` method the name
607 of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
608 back will contain the name of the synonym and the "real" option (such as
609 ``('bg', 'background')``).
610
611 +-------+---------------------------------+--------------+
612 | Index | Meaning | Example |
613 +=======+=================================+==============+
614 | 0 | option name | ``'relief'`` |
615 +-------+---------------------------------+--------------+
616 | 1 | option name for database lookup | ``'relief'`` |
617 +-------+---------------------------------+--------------+
618 | 2 | option class for database | ``'Relief'`` |
619 | | lookup | |
620 +-------+---------------------------------+--------------+
621 | 3 | default value | ``'raised'`` |
622 +-------+---------------------------------+--------------+
623 | 4 | current value | ``'groove'`` |
624 +-------+---------------------------------+--------------+
625
626 Example::
627
628 >>> print(fred.config())
629 {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}
630
631 Of course, the dictionary printed will include all the options available and
632 their values. This is meant only as an example.
633
634
635 The Packer
636 ^^^^^^^^^^
637
638 .. index:: single: packing (widgets)
639
640 The packer is one of Tk's geometry-management mechanisms. Geometry managers
641 are used to specify the relative positioning of widgets within their container.
642 In contrast to the more cumbersome *placer* (which is
643 used less commonly, and we do not cover here), the packer takes qualitative
644 relationship specification - *above*, *to the left of*, *filling*, etc - and
645 works everything out to determine the exact placement coordinates for you.
646
647 The size of any container widget is determined by the size of the "content widgets"
648 inside. The packer is used to control where content widgets appear inside the
649 container into which they are packed. You can pack widgets into frames, and frames
650 into other frames, in order to achieve the kind of layout you desire.
651 Additionally, the arrangement is dynamically adjusted to accommodate incremental
652 changes to the configuration, once it is packed.
653
654 Note that widgets do not appear until they have had their geometry specified
655 with a geometry manager. It's a common early mistake to leave out the geometry
656 specification, and then be surprised when the widget is created but nothing
657 appears. A widget will appear only after it has had, for example, the packer's
658 :meth:`pack` method applied to it.
659
660 The pack() method can be called with keyword-option/value pairs that control
661 where the widget is to appear within its container, and how it is to behave when
662 the main application window is resized. Here are some examples::
663
664 fred.pack() # defaults to side = "top"
665 fred.pack(side="left")
666 fred.pack(expand=1)
667
668
669 Packer Options
670 ^^^^^^^^^^^^^^
671
672 For more extensive information on the packer and the options that it can take,
673 see the man pages and page 183 of John Ousterhout's book.
674
675 anchor
676 Anchor type. Denotes where the packer is to place each content in its parcel.
677
678 expand
679 Boolean, ``0`` or ``1``.
680
681 fill
682 Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
683
684 ipadx and ipady
685 A distance - designating internal padding on each side of the content.
686
687 padx and pady
688 A distance - designating external padding on each side of the content.
689
690 side
691 Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
692
693
694 Coupling Widget Variables
695 ^^^^^^^^^^^^^^^^^^^^^^^^^
696
697 The current-value setting of some widgets (like text entry widgets) can be
698 connected directly to application variables by using special options. These
699 options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
700 ``value``. This connection works both ways: if the variable changes for any
701 reason, the widget it's connected to will be updated to reflect the new value.
702
703 Unfortunately, in the current implementation of :mod:`!tkinter` it is not
704 possible to hand over an arbitrary Python variable to a widget through a
705 ``variable`` or ``textvariable`` option. The only kinds of variables for which
706 this works are variables that are subclassed from a class called Variable,
707 defined in :mod:`!tkinter`.
708
709 There are many useful subclasses of Variable already defined:
710 :class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
711 :class:`BooleanVar`. To read the current value of such a variable, call the
712 :meth:`get` method on it, and to change its value you call the :meth:`!set`
713 method. If you follow this protocol, the widget will always track the value of
714 the variable, with no further intervention on your part.
715
716 For example::
717
718 import tkinter as tk
719
720 class App(tk.Frame):
721 def __init__(self, master):
722 super().__init__(master)
723 self.pack()
724
725 self.entrythingy = tk.Entry()
726 self.entrythingy.pack()
727
728 # Create the application variable.
729 self.contents = tk.StringVar()
730 # Set it to some value.
731 self.contents.set("this is a variable")
732 # Tell the entry widget to watch this variable.
733 self.entrythingy["textvariable"] = self.contents
734
735 # Define a callback for when the user hits return.
736 # It prints the current value of the variable.
737 self.entrythingy.bind('<Key-Return>',
738 self.print_contents)
739
740 def print_contents(self, event):
741 print("Hi. The current entry content is:",
742 self.contents.get())
743
744 root = tk.Tk()
745 myapp = App(root)
746 myapp.mainloop()
747
748 The Window Manager
749 ^^^^^^^^^^^^^^^^^^
750
751 .. index:: single: window manager (widgets)
752
753 In Tk, there is a utility command, ``wm``, for interacting with the window
754 manager. Options to the ``wm`` command allow you to control things like titles,
755 placement, icon bitmaps, and the like. In :mod:`!tkinter`, these commands have
756 been implemented as methods on the :class:`Wm` class. Toplevel widgets are
757 subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
758 directly.
759
760 To get at the toplevel window that contains a given widget, you can often just
761 refer to the widget's :attr:`master`. Of course if the widget has been packed inside of
762 a frame, the :attr:`!master` won't represent a toplevel window. To get at the toplevel
763 window that contains an arbitrary widget, you can call the :meth:`_root` method.
764 This method begins with an underscore to denote the fact that this function is
765 part of the implementation, and not an interface to Tk functionality.
766
767 Here are some examples of typical usage::
768
769 import tkinter as tk
770
771 class App(tk.Frame):
772 def __init__(self, master=None):
773 super().__init__(master)
774 self.pack()
775
776 # create the application
777 myapp = App()
778
779 #
780 # here are method calls to the window manager class
781 #
782 myapp.master.title("My Do-Nothing Application")
783 myapp.master.maxsize(1000, 400)
784
785 # start the program
786 myapp.mainloop()
787
788
789 Tk Option Data Types
790 ^^^^^^^^^^^^^^^^^^^^
791
792 .. index:: single: Tk Option Data Types
793
794 anchor
795 Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
796 ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
797
798 bitmap
799 There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
800 ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
801 ``'warning'``. To specify an X bitmap filename, give the full path to the file,
802 preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
803
804 boolean
805 You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.
806
807 callback
808 This is any Python function that takes no arguments. For example::
809
810 def print_it():
811 print("hi there")
812 fred["command"] = print_it
813
814 color
815 Colors can be given as the names of X colors in the rgb.txt file, or as strings
816 representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit:
817 ``"#RRRGGGBBB"``, or 16 bit: ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
818 represent any legal hex digit. See page 160 of Ousterhout's book for details.
819
820 cursor
821 The standard X cursor names from :file:`cursorfont.h` can be used, without the
822 ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
823 string ``"hand2"``. You can also specify a bitmap and mask file of your own.
824 See page 179 of Ousterhout's book.
825
826 distance
827 Screen distances can be specified in either pixels or absolute distances.
828 Pixels are given as numbers and absolute distances as strings, with the trailing
829 character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
830 millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
831 as ``"3.5i"``.
832
833 font
834 Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
835 positive numbers are measured in points; sizes with negative numbers are
836 measured in pixels.
837
838 geometry
839 This is a string of the form ``widthxheight``, where width and height are
840 measured in pixels for most widgets (in characters for widgets displaying text).
841 For example: ``fred["geometry"] = "200x100"``.
842
843 justify
844 Legal values are the strings: ``"left"``, ``"center"``, and ``"right"``.
845
846 region
847 This is a string with four space-delimited elements, each of which is a legal
848 distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
849 ``"3c 2c 4c 10.43c"`` are all legal regions.
850
851 relief
852 Determines what the border style of a widget will be. Legal values are:
853 ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
854
855 scrollcommand
856 This is almost always the :meth:`!set` method of some scrollbar widget, but can
857 be any widget method that takes a single argument.
858
859 wrap
860 Must be one of: ``"none"``, ``"char"``, or ``"word"``.
861
862 .. _Bindings-and-Events:
863
864 Bindings and Events
865 ^^^^^^^^^^^^^^^^^^^
866
867 .. index::
868 single: bind (widgets)
869 single: events (widgets)
870
871 The bind method from the widget command allows you to watch for certain events
872 and to have a callback function trigger when that event type occurs. The form
873 of the bind method is::
874
875 def bind(self, sequence, func, add=''):
876
877 where:
878
879 sequence
880 is a string that denotes the target kind of event. (See the
881 :manpage:`bind(3tk)` man page, and page 201 of John Ousterhout's book,
882 :title-reference:`Tcl and the Tk Toolkit (2nd edition)`, for details).
883
884 func
885 is a Python function, taking one argument, to be invoked when the event occurs.
886 An Event instance will be passed as the argument. (Functions deployed this way
887 are commonly known as *callbacks*.)
888
889 add
890 is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
891 this binding is to replace any other bindings that this event is associated
892 with. Passing a ``'+'`` means that this function is to be added to the list
893 of functions bound to this event type.
894
895 For example::
896
897 def turn_red(self, event):
898 event.widget["activeforeground"] = "red"
899
900 self.button.bind("<Enter>", self.turn_red)
901
902 Notice how the widget field of the event is being accessed in the
903 ``turn_red()`` callback. This field contains the widget that caught the X
904 event. The following table lists the other event fields you can access, and how
905 they are denoted in Tk, which can be useful when referring to the Tk man pages.
906
907 +----+---------------------+----+---------------------+
908 | Tk | Tkinter Event Field | Tk | Tkinter Event Field |
909 +====+=====================+====+=====================+
910 | %f | focus | %A | char |
911 +----+---------------------+----+---------------------+
912 | %h | height | %E | send_event |
913 +----+---------------------+----+---------------------+
914 | %k | keycode | %K | keysym |
915 +----+---------------------+----+---------------------+
916 | %s | state | %N | keysym_num |
917 +----+---------------------+----+---------------------+
918 | %t | time | %T | type |
919 +----+---------------------+----+---------------------+
920 | %w | width | %W | widget |
921 +----+---------------------+----+---------------------+
922 | %x | x | %X | x_root |
923 +----+---------------------+----+---------------------+
924 | %y | y | %Y | y_root |
925 +----+---------------------+----+---------------------+
926
927
928 The index Parameter
929 ^^^^^^^^^^^^^^^^^^^
930
931 A number of widgets require "index" parameters to be passed. These are used to
932 point at a specific place in a Text widget, or to particular characters in an
933 Entry widget, or to particular menu items in a Menu widget.
934
935 Entry widget indexes (index, view index, etc.)
936 Entry widgets have options that refer to character positions in the text being
937 displayed. You can use these :mod:`!tkinter` functions to access these special
938 points in text widgets:
939
940 Text widget indexes
941 The index notation for Text widgets is very rich and is best described in the Tk
942 man pages.
943
944 Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
945 Some options and methods for menus manipulate specific menu entries. Anytime a
946 menu index is needed for an option or a parameter, you may pass in:
947
948 * an integer which refers to the numeric position of the entry in the widget,
949 counted from the top, starting with 0;
950
951 * the string ``"active"``, which refers to the menu position that is currently
952 under the cursor;
953
954 * the string ``"last"`` which refers to the last menu item;
955
956 * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
957 as a y pixel coordinate in the menu's coordinate system;
958
959 * the string ``"none"``, which indicates no menu entry at all, most often used
960 with menu.activate() to deactivate all entries, and finally,
961
962 * a text string that is pattern matched against the label of the menu entry, as
963 scanned from the top of the menu to the bottom. Note that this index type is
964 considered after all the others, which means that matches for menu items
965 labelled ``last``, ``active``, or ``none`` may be interpreted as the above
966 literals, instead.
967
968
969 Images
970 ^^^^^^
971
972 Images of different formats can be created through the corresponding subclass
973 of :class:`tkinter.Image`:
974
975 * :class:`BitmapImage` for images in XBM format.
976
977 * :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter
978 is supported starting with Tk 8.6.
979
980 Either type of image is created through either the ``file`` or the ``data``
981 option (other options are available as well).
982
983 .. versionchanged:: 3.13
984 Added the :class:`!PhotoImage` method :meth:`!copy_replace` to copy a region
985 from one image to other image, possibly with pixel zooming and/or
986 subsampling.
987 Add *from_coords* parameter to :class:`!PhotoImage` methods :meth:`!copy`,
988 :meth:`!zoom` and :meth:`!subsample`.
989 Add *zoom* and *subsample* parameters to :class:`!PhotoImage` method
990 :meth:`!copy`.
991
992 The image object can then be used wherever an ``image`` option is supported by
993 some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
994 reference to the image. When the last Python reference to the image object is
995 deleted, the image data is deleted as well, and Tk will display an empty box
996 wherever the image was used.
997
998 .. seealso::
999
1000 The `Pillow <https://python-pillow.org/>`_ package adds support for
1001 formats such as BMP, JPEG, TIFF, and WebP, among others.
1002
1003 .. _tkinter-file-handlers:
1004
1005 File Handlers
1006 -------------
1007
1008 Tk allows you to register and unregister a callback function which will be
1009 called from the Tk mainloop when I/O is possible on a file descriptor.
1010 Only one handler may be registered per file descriptor. Example code::
1011
1012 import tkinter
1013 widget = tkinter.Tk()
1014 mask = tkinter.READABLE | tkinter.WRITABLE
1015 widget.tk.createfilehandler(file, mask, callback)
1016 ...
1017 widget.tk.deletefilehandler(file)
1018
1019 This feature is not available on Windows.
1020
1021 Since you don't know how many bytes are available for reading, you may not
1022 want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
1023 :meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods,
1024 since these will insist on reading a predefined number of bytes.
1025 For sockets, the :meth:`~socket.socket.recv` or
1026 :meth:`~socket.socket.recvfrom` methods will work fine; for other files,
1027 use raw reads or ``os.read(file.fileno(), maxbytecount)``.
1028
1029
1030 .. method:: Widget.tk.createfilehandler(file, mask, func)
1031
1032 Registers the file handler callback function *func*. The *file* argument
1033 may either be an object with a :meth:`~io.IOBase.fileno` method (such as
1034 a file or socket object), or an integer file descriptor. The *mask*
1035 argument is an ORed combination of any of the three constants below.
1036 The callback is called as follows::
1037
1038 callback(file, mask)
1039
1040
1041 .. method:: Widget.tk.deletefilehandler(file)
1042
1043 Unregisters a file handler.
1044
1045
1046 .. data:: READABLE
1047 WRITABLE
1048 EXCEPTION
1049
1050 Constants used in the *mask* arguments.