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