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