17db96d56Sopenharmony_ci:mod:`tkinter` --- Python interface to Tcl/Tk
27db96d56Sopenharmony_ci=============================================
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci.. module:: tkinter
57db96d56Sopenharmony_ci   :synopsis: Interface to Tcl/Tk for graphical user interfaces
67db96d56Sopenharmony_ci
77db96d56Sopenharmony_ci.. moduleauthor:: Guido van Rossum <guido@Python.org>
87db96d56Sopenharmony_ci
97db96d56Sopenharmony_ci**Source code:** :source:`Lib/tkinter/__init__.py`
107db96d56Sopenharmony_ci
117db96d56Sopenharmony_ci--------------
127db96d56Sopenharmony_ci
137db96d56Sopenharmony_ciThe :mod:`tkinter` package ("Tk interface") is the standard Python interface to
147db96d56Sopenharmony_cithe Tcl/Tk GUI toolkit.  Both Tk and :mod:`tkinter` are available on most Unix
157db96d56Sopenharmony_ciplatforms, including macOS, as well as on Windows systems.
167db96d56Sopenharmony_ci
177db96d56Sopenharmony_ciRunning ``python -m tkinter`` from the command line should open a window
187db96d56Sopenharmony_cidemonstrating a simple Tk interface, letting you know that :mod:`tkinter` is
197db96d56Sopenharmony_ciproperly installed on your system, and also showing what version of Tcl/Tk is
207db96d56Sopenharmony_ciinstalled, so you can read the Tcl/Tk documentation specific to that version.
217db96d56Sopenharmony_ci
227db96d56Sopenharmony_ciTkinter supports a range of Tcl/Tk versions, built either with or
237db96d56Sopenharmony_ciwithout thread support. The official Python binary release bundles Tcl/Tk 8.6
247db96d56Sopenharmony_cithreaded. See the source code for the :mod:`_tkinter` module
257db96d56Sopenharmony_cifor more information about supported versions.
267db96d56Sopenharmony_ci
277db96d56Sopenharmony_ciTkinter is not a thin wrapper, but adds a fair amount of its own logic to
287db96d56Sopenharmony_cimake the experience more pythonic. This documentation will concentrate on these
297db96d56Sopenharmony_ciadditions and changes, and refer to the official Tcl/Tk documentation for
307db96d56Sopenharmony_cidetails that are unchanged.
317db96d56Sopenharmony_ci
327db96d56Sopenharmony_ci.. note::
337db96d56Sopenharmony_ci
347db96d56Sopenharmony_ci   Tcl/Tk 8.5 (2007) introduced a modern set of themed user interface components
357db96d56Sopenharmony_ci   along with a new API to use them. Both old and new APIs are still available.
367db96d56Sopenharmony_ci   Most documentation you will find online still uses the old API and
377db96d56Sopenharmony_ci   can be woefully outdated.
387db96d56Sopenharmony_ci
397db96d56Sopenharmony_ci.. seealso::
407db96d56Sopenharmony_ci
417db96d56Sopenharmony_ci   * `TkDocs <https://tkdocs.com/>`_
427db96d56Sopenharmony_ci      Extensive tutorial on creating user interfaces with Tkinter.  Explains key concepts,
437db96d56Sopenharmony_ci      and illustrates recommended approaches using the modern API.
447db96d56Sopenharmony_ci
457db96d56Sopenharmony_ci   * `Tkinter 8.5 reference: a GUI for Python <https://www.tkdocs.com/shipman/>`_
467db96d56Sopenharmony_ci      Reference documentation for Tkinter 8.5 detailing available classes, methods, and options.
477db96d56Sopenharmony_ci
487db96d56Sopenharmony_ci   Tcl/Tk Resources:
497db96d56Sopenharmony_ci
507db96d56Sopenharmony_ci   * `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
517db96d56Sopenharmony_ci      Comprehensive reference to each of the underlying Tcl/Tk commands used by Tkinter.
527db96d56Sopenharmony_ci
537db96d56Sopenharmony_ci   * `Tcl/Tk Home Page <https://www.tcl.tk>`_
547db96d56Sopenharmony_ci      Additional documentation, and links to Tcl/Tk core development.
557db96d56Sopenharmony_ci
567db96d56Sopenharmony_ci   Books:
577db96d56Sopenharmony_ci
587db96d56Sopenharmony_ci   * `Modern Tkinter for Busy Python Developers <https://tkdocs.com/book.html>`_
597db96d56Sopenharmony_ci      By Mark Roseman. (ISBN 978-1999149567)
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ci   * `Python and Tkinter Programming <https://www.packtpub.com/product/python-gui-programming-with-tkinter/9781788835886>`_
627db96d56Sopenharmony_ci      By Alan Moore. (ISBN 978-1788835886)
637db96d56Sopenharmony_ci
647db96d56Sopenharmony_ci   * `Programming Python <https://learning-python.com/about-pp4e.html>`_
657db96d56Sopenharmony_ci      By Mark Lutz; has excellent coverage of Tkinter. (ISBN 978-0596158101)
667db96d56Sopenharmony_ci
677db96d56Sopenharmony_ci   * `Tcl and the Tk Toolkit (2nd edition)  <https://www.amazon.com/exec/obidos/ASIN/032133633X>`_
687db96d56Sopenharmony_ci      By John Ousterhout, inventor of Tcl/Tk, and Ken Jones; does not cover Tkinter. (ISBN 978-0321336330)
697db96d56Sopenharmony_ci
707db96d56Sopenharmony_ci
717db96d56Sopenharmony_ciArchitecture
727db96d56Sopenharmony_ci------------
737db96d56Sopenharmony_ci
747db96d56Sopenharmony_ciTcl/Tk is not a single library but rather consists of a few distinct
757db96d56Sopenharmony_cimodules, each with separate functionality and its own official
767db96d56Sopenharmony_cidocumentation. Python's binary releases also ship an add-on module
777db96d56Sopenharmony_citogether with it.
787db96d56Sopenharmony_ci
797db96d56Sopenharmony_ciTcl
807db96d56Sopenharmony_ci   Tcl is a dynamic interpreted programming language, just like Python. Though
817db96d56Sopenharmony_ci   it can be used on its own as a general-purpose programming language, it is
827db96d56Sopenharmony_ci   most commonly embedded into C applications as a scripting engine or an
837db96d56Sopenharmony_ci   interface to the Tk toolkit. The Tcl library has a C interface to
847db96d56Sopenharmony_ci   create and manage one or more instances of a Tcl interpreter, run Tcl
857db96d56Sopenharmony_ci   commands and scripts in those instances, and add custom commands
867db96d56Sopenharmony_ci   implemented in either Tcl or C. Each interpreter has an event queue,
877db96d56Sopenharmony_ci   and there are facilities to send events to it and process them.
887db96d56Sopenharmony_ci   Unlike Python, Tcl's execution model is designed around cooperative
897db96d56Sopenharmony_ci   multitasking, and Tkinter bridges this difference
907db96d56Sopenharmony_ci   (see `Threading model`_ for details).
917db96d56Sopenharmony_ci
927db96d56Sopenharmony_ciTk
937db96d56Sopenharmony_ci   Tk is a `Tcl package <https://wiki.tcl-lang.org/37432>`_ implemented in C
947db96d56Sopenharmony_ci   that adds custom commands to create and manipulate GUI widgets. Each
957db96d56Sopenharmony_ci   :class:`Tk` object embeds its own Tcl interpreter instance with Tk loaded into
967db96d56Sopenharmony_ci   it. Tk's widgets are very customizable, though at the cost of a dated appearance.
977db96d56Sopenharmony_ci   Tk uses Tcl's event queue to generate and process GUI events.
987db96d56Sopenharmony_ci
997db96d56Sopenharmony_ciTtk
1007db96d56Sopenharmony_ci   Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better
1017db96d56Sopenharmony_ci   appearance on different platforms than many of the classic Tk widgets.
1027db96d56Sopenharmony_ci   Ttk is distributed as part of Tk, starting with Tk version 8.5. Python
1037db96d56Sopenharmony_ci   bindings are provided in a separate module, :mod:`tkinter.ttk`.
1047db96d56Sopenharmony_ci
1057db96d56Sopenharmony_ciInternally, Tk and Ttk use facilities of the underlying operating system,
1067db96d56Sopenharmony_cii.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.
1077db96d56Sopenharmony_ci
1087db96d56Sopenharmony_ciWhen your Python application uses a class in Tkinter, e.g., to create a widget,
1097db96d56Sopenharmony_cithe :mod:`tkinter` module first assembles a Tcl/Tk command string. It passes that
1107db96d56Sopenharmony_ciTcl command string to an internal :mod:`_tkinter` binary module, which then
1117db96d56Sopenharmony_cicalls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the
1127db96d56Sopenharmony_ciTk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI.
1137db96d56Sopenharmony_ci
1147db96d56Sopenharmony_ci
1157db96d56Sopenharmony_ciTkinter Modules
1167db96d56Sopenharmony_ci---------------
1177db96d56Sopenharmony_ci
1187db96d56Sopenharmony_ciSupport for Tkinter is spread across several modules. Most applications will need the
1197db96d56Sopenharmony_cimain :mod:`tkinter` module, as well as the :mod:`tkinter.ttk` module, which provides
1207db96d56Sopenharmony_cithe modern themed widget set and API::
1217db96d56Sopenharmony_ci
1227db96d56Sopenharmony_ci
1237db96d56Sopenharmony_ci   from tkinter import *
1247db96d56Sopenharmony_ci   from tkinter import ttk
1257db96d56Sopenharmony_ci
1267db96d56Sopenharmony_ci
1277db96d56Sopenharmony_ci.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=True, sync=False, use=None)
1287db96d56Sopenharmony_ci
1297db96d56Sopenharmony_ci   Construct a toplevel Tk widget, which is usually the main window of an
1307db96d56Sopenharmony_ci   application, and initialize a Tcl interpreter for this widget.  Each
1317db96d56Sopenharmony_ci   instance has its own associated Tcl interpreter.
1327db96d56Sopenharmony_ci
1337db96d56Sopenharmony_ci   The :class:`Tk` class is typically instantiated using all default values.
1347db96d56Sopenharmony_ci   However, the following keyword arguments are currently recognized:
1357db96d56Sopenharmony_ci
1367db96d56Sopenharmony_ci   *screenName*
1377db96d56Sopenharmony_ci      When given (as a string), sets the :envvar:`DISPLAY` environment
1387db96d56Sopenharmony_ci      variable. (X11 only)
1397db96d56Sopenharmony_ci   *baseName*
1407db96d56Sopenharmony_ci      Name of the profile file.  By default, *baseName* is derived from the
1417db96d56Sopenharmony_ci      program name (``sys.argv[0]``).
1427db96d56Sopenharmony_ci   *className*
1437db96d56Sopenharmony_ci      Name of the widget class.  Used as a profile file and also as the name
1447db96d56Sopenharmony_ci      with which Tcl is invoked (*argv0* in *interp*).
1457db96d56Sopenharmony_ci   *useTk*
1467db96d56Sopenharmony_ci      If ``True``, initialize the Tk subsystem.  The :func:`tkinter.Tcl() <Tcl>`
1477db96d56Sopenharmony_ci      function sets this to ``False``.
1487db96d56Sopenharmony_ci   *sync*
1497db96d56Sopenharmony_ci      If ``True``, execute all X server commands synchronously, so that errors
1507db96d56Sopenharmony_ci      are reported immediately.  Can be used for debugging. (X11 only)
1517db96d56Sopenharmony_ci   *use*
1527db96d56Sopenharmony_ci      Specifies the *id* of the window in which to embed the application,
1537db96d56Sopenharmony_ci      instead of it being created as an independent toplevel window. *id* must
1547db96d56Sopenharmony_ci      be specified in the same way as the value for the -use option for
1557db96d56Sopenharmony_ci      toplevel widgets (that is, it has a form like that returned by
1567db96d56Sopenharmony_ci      :meth:`winfo_id`).
1577db96d56Sopenharmony_ci
1587db96d56Sopenharmony_ci      Note that on some platforms this will only work correctly if *id* refers
1597db96d56Sopenharmony_ci      to a Tk frame or toplevel that has its -container option enabled.
1607db96d56Sopenharmony_ci
1617db96d56Sopenharmony_ci   :class:`Tk` reads and interprets profile files, named
1627db96d56Sopenharmony_ci   :file:`.{className}.tcl` and :file:`.{baseName}.tcl`, into the Tcl
1637db96d56Sopenharmony_ci   interpreter and calls :func:`exec` on the contents of
1647db96d56Sopenharmony_ci   :file:`.{className}.py` and :file:`.{baseName}.py`.  The path for the
1657db96d56Sopenharmony_ci   profile files is the :envvar:`HOME` environment variable or, if that
1667db96d56Sopenharmony_ci   isn't defined, then :attr:`os.curdir`.
1677db96d56Sopenharmony_ci
1687db96d56Sopenharmony_ci   .. attribute:: tk
1697db96d56Sopenharmony_ci
1707db96d56Sopenharmony_ci      The Tk application object created by instantiating :class:`Tk`.  This
1717db96d56Sopenharmony_ci      provides access to the Tcl interpreter.  Each widget that is attached
1727db96d56Sopenharmony_ci      the same instance of :class:`Tk` has the same value for its :attr:`tk`
1737db96d56Sopenharmony_ci      attribute.
1747db96d56Sopenharmony_ci
1757db96d56Sopenharmony_ci   .. attribute:: master
1767db96d56Sopenharmony_ci
1777db96d56Sopenharmony_ci      The widget object that contains this widget.  For :class:`Tk`, the
1787db96d56Sopenharmony_ci      *master* is :const:`None` because it is the main window.  The terms
1797db96d56Sopenharmony_ci      *master* and *parent* are similar and sometimes used interchangeably
1807db96d56Sopenharmony_ci      as argument names; however, calling :meth:`winfo_parent` returns a
1817db96d56Sopenharmony_ci      string of the widget name whereas :attr:`master` returns the object.
1827db96d56Sopenharmony_ci      *parent*/*child* reflects the tree-like relationship while
1837db96d56Sopenharmony_ci      *master*/*slave* reflects the container structure.
1847db96d56Sopenharmony_ci
1857db96d56Sopenharmony_ci   .. attribute:: children
1867db96d56Sopenharmony_ci
1877db96d56Sopenharmony_ci      The immediate descendants of this widget as a :class:`dict` with the
1887db96d56Sopenharmony_ci      child widget names as the keys and the child instance objects as the
1897db96d56Sopenharmony_ci      values.
1907db96d56Sopenharmony_ci
1917db96d56Sopenharmony_ci
1927db96d56Sopenharmony_ci.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=False)
1937db96d56Sopenharmony_ci
1947db96d56Sopenharmony_ci   The :func:`Tcl` function is a factory function which creates an object much like
1957db96d56Sopenharmony_ci   that created by the :class:`Tk` class, except that it does not initialize the Tk
1967db96d56Sopenharmony_ci   subsystem.  This is most often useful when driving the Tcl interpreter in an
1977db96d56Sopenharmony_ci   environment where one doesn't want to create extraneous toplevel windows, or
1987db96d56Sopenharmony_ci   where one cannot (such as Unix/Linux systems without an X server).  An object
1997db96d56Sopenharmony_ci   created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
2007db96d56Sopenharmony_ci   subsystem initialized) by calling its :meth:`loadtk` method.
2017db96d56Sopenharmony_ci
2027db96d56Sopenharmony_ci
2037db96d56Sopenharmony_ciThe modules that provide Tk support include:
2047db96d56Sopenharmony_ci
2057db96d56Sopenharmony_ci:mod:`tkinter`
2067db96d56Sopenharmony_ci   Main Tkinter module.
2077db96d56Sopenharmony_ci
2087db96d56Sopenharmony_ci:mod:`tkinter.colorchooser`
2097db96d56Sopenharmony_ci   Dialog to let the user choose a color.
2107db96d56Sopenharmony_ci
2117db96d56Sopenharmony_ci:mod:`tkinter.commondialog`
2127db96d56Sopenharmony_ci   Base class for the dialogs defined in the other modules listed here.
2137db96d56Sopenharmony_ci
2147db96d56Sopenharmony_ci:mod:`tkinter.filedialog`
2157db96d56Sopenharmony_ci   Common dialogs to allow the user to specify a file to open or save.
2167db96d56Sopenharmony_ci
2177db96d56Sopenharmony_ci:mod:`tkinter.font`
2187db96d56Sopenharmony_ci   Utilities to help work with fonts.
2197db96d56Sopenharmony_ci
2207db96d56Sopenharmony_ci:mod:`tkinter.messagebox`
2217db96d56Sopenharmony_ci   Access to standard Tk dialog boxes.
2227db96d56Sopenharmony_ci
2237db96d56Sopenharmony_ci:mod:`tkinter.scrolledtext`
2247db96d56Sopenharmony_ci   Text widget with a vertical scroll bar built in.
2257db96d56Sopenharmony_ci
2267db96d56Sopenharmony_ci:mod:`tkinter.simpledialog`
2277db96d56Sopenharmony_ci   Basic dialogs and convenience functions.
2287db96d56Sopenharmony_ci
2297db96d56Sopenharmony_ci:mod:`tkinter.ttk`
2307db96d56Sopenharmony_ci   Themed widget set introduced in Tk 8.5, providing modern alternatives
2317db96d56Sopenharmony_ci   for many of the classic widgets in the main :mod:`tkinter` module.
2327db96d56Sopenharmony_ci
2337db96d56Sopenharmony_ciAdditional modules:
2347db96d56Sopenharmony_ci
2357db96d56Sopenharmony_ci:mod:`_tkinter`
2367db96d56Sopenharmony_ci   A binary module that contains the low-level interface to Tcl/Tk.
2377db96d56Sopenharmony_ci   It is automatically imported by the main :mod:`tkinter` module,
2387db96d56Sopenharmony_ci   and should never be used directly by application programmers.
2397db96d56Sopenharmony_ci   It is usually a shared library (or DLL), but might in some cases be
2407db96d56Sopenharmony_ci   statically linked with the Python interpreter.
2417db96d56Sopenharmony_ci
2427db96d56Sopenharmony_ci:mod:`idlelib`
2437db96d56Sopenharmony_ci   Python's Integrated Development and Learning Environment (IDLE). Based
2447db96d56Sopenharmony_ci   on :mod:`tkinter`.
2457db96d56Sopenharmony_ci
2467db96d56Sopenharmony_ci:mod:`tkinter.constants`
2477db96d56Sopenharmony_ci   Symbolic constants that can be used in place of strings when passing
2487db96d56Sopenharmony_ci   various parameters to Tkinter calls. Automatically imported by the
2497db96d56Sopenharmony_ci   main :mod:`tkinter` module.
2507db96d56Sopenharmony_ci
2517db96d56Sopenharmony_ci:mod:`tkinter.dnd`
2527db96d56Sopenharmony_ci   (experimental) Drag-and-drop support for :mod:`tkinter`. This will
2537db96d56Sopenharmony_ci   become deprecated when it is replaced with the Tk DND.
2547db96d56Sopenharmony_ci
2557db96d56Sopenharmony_ci:mod:`tkinter.tix`
2567db96d56Sopenharmony_ci   (deprecated) An older third-party Tcl/Tk package that adds several new
2577db96d56Sopenharmony_ci   widgets. Better alternatives for most can be found in :mod:`tkinter.ttk`.
2587db96d56Sopenharmony_ci
2597db96d56Sopenharmony_ci:mod:`turtle`
2607db96d56Sopenharmony_ci   Turtle graphics in a Tk window.
2617db96d56Sopenharmony_ci
2627db96d56Sopenharmony_ci
2637db96d56Sopenharmony_ciTkinter Life Preserver
2647db96d56Sopenharmony_ci----------------------
2657db96d56Sopenharmony_ci
2667db96d56Sopenharmony_ciThis section is not designed to be an exhaustive tutorial on either Tk or
2677db96d56Sopenharmony_ciTkinter.  For that, refer to one of the external resources noted earlier.
2687db96d56Sopenharmony_ciInstead, this section provides a very quick orientation to what a Tkinter
2697db96d56Sopenharmony_ciapplication looks like, identifies foundational Tk concepts, and
2707db96d56Sopenharmony_ciexplains how the Tkinter wrapper is structured.
2717db96d56Sopenharmony_ci
2727db96d56Sopenharmony_ciThe remainder of this section will help you to identify the classes,
2737db96d56Sopenharmony_cimethods, and options you'll need in your Tkinter application, and where to
2747db96d56Sopenharmony_cifind more detailed documentation on them, including in the official Tcl/Tk
2757db96d56Sopenharmony_cireference manual.
2767db96d56Sopenharmony_ci
2777db96d56Sopenharmony_ci
2787db96d56Sopenharmony_ciA Hello World Program
2797db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^
2807db96d56Sopenharmony_ci
2817db96d56Sopenharmony_ciWe'll start by walking through a "Hello World" application in Tkinter. This
2827db96d56Sopenharmony_ciisn't the smallest one we could write, but has enough to illustrate some
2837db96d56Sopenharmony_cikey concepts you'll need to know.
2847db96d56Sopenharmony_ci
2857db96d56Sopenharmony_ci::
2867db96d56Sopenharmony_ci
2877db96d56Sopenharmony_ci    from tkinter import *
2887db96d56Sopenharmony_ci    from tkinter import ttk
2897db96d56Sopenharmony_ci    root = Tk()
2907db96d56Sopenharmony_ci    frm = ttk.Frame(root, padding=10)
2917db96d56Sopenharmony_ci    frm.grid()
2927db96d56Sopenharmony_ci    ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
2937db96d56Sopenharmony_ci    ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
2947db96d56Sopenharmony_ci    root.mainloop()
2957db96d56Sopenharmony_ci
2967db96d56Sopenharmony_ci
2977db96d56Sopenharmony_ciAfter the imports, the next line creates an instance of the :class:`Tk` class,
2987db96d56Sopenharmony_ciwhich initializes Tk and creates its associated Tcl interpreter. It also
2997db96d56Sopenharmony_cicreates a toplevel window, known as the root window, which serves as the main
3007db96d56Sopenharmony_ciwindow of the application.
3017db96d56Sopenharmony_ci
3027db96d56Sopenharmony_ciThe following line creates a frame widget, which in this case will contain
3037db96d56Sopenharmony_cia label and a button we'll create next. The frame is fit inside the root
3047db96d56Sopenharmony_ciwindow.
3057db96d56Sopenharmony_ci
3067db96d56Sopenharmony_ciThe next line creates a label widget holding a static text string. The
3077db96d56Sopenharmony_ci:meth:`grid` method is used to specify the relative layout (position) of the
3087db96d56Sopenharmony_cilabel within its containing frame widget, similar to how tables in HTML work.
3097db96d56Sopenharmony_ci
3107db96d56Sopenharmony_ciA button widget is then created, and placed to the right of the label. When
3117db96d56Sopenharmony_cipressed, it will call the :meth:`destroy` method of the root window.
3127db96d56Sopenharmony_ci
3137db96d56Sopenharmony_ciFinally, the :meth:`mainloop` method puts everything on the display, and
3147db96d56Sopenharmony_ciresponds to user input until the program terminates.
3157db96d56Sopenharmony_ci
3167db96d56Sopenharmony_ci
3177db96d56Sopenharmony_ci
3187db96d56Sopenharmony_ciImportant Tk Concepts
3197db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^
3207db96d56Sopenharmony_ci
3217db96d56Sopenharmony_ciEven this simple program illustrates the following key Tk concepts:
3227db96d56Sopenharmony_ci
3237db96d56Sopenharmony_ciwidgets
3247db96d56Sopenharmony_ci  A Tkinter user interface is made up of individual *widgets*. Each widget is
3257db96d56Sopenharmony_ci  represented as a Python object, instantiated from classes like
3267db96d56Sopenharmony_ci  :class:`ttk.Frame`, :class:`ttk.Label`, and :class:`ttk.Button`.
3277db96d56Sopenharmony_ci
3287db96d56Sopenharmony_ciwidget hierarchy
3297db96d56Sopenharmony_ci  Widgets are arranged in a *hierarchy*. The label and button were contained
3307db96d56Sopenharmony_ci  within a frame, which in turn was contained within the root window. When
3317db96d56Sopenharmony_ci  creating each *child* widget, its *parent* widget is passed as the first
3327db96d56Sopenharmony_ci  argument to the widget constructor.
3337db96d56Sopenharmony_ci
3347db96d56Sopenharmony_ciconfiguration options
3357db96d56Sopenharmony_ci  Widgets have *configuration options*, which modify their appearance and
3367db96d56Sopenharmony_ci  behavior, such as the text to display in a label or button. Different
3377db96d56Sopenharmony_ci  classes of widgets will have different sets of options.
3387db96d56Sopenharmony_ci
3397db96d56Sopenharmony_cigeometry management
3407db96d56Sopenharmony_ci  Widgets aren't automatically added to the user interface when they are
3417db96d56Sopenharmony_ci  created. A *geometry manager* like ``grid`` controls where in the
3427db96d56Sopenharmony_ci  user interface they are placed.
3437db96d56Sopenharmony_ci
3447db96d56Sopenharmony_cievent loop
3457db96d56Sopenharmony_ci  Tkinter reacts to user input, changes from your program, and even refreshes
3467db96d56Sopenharmony_ci  the display only when actively running an *event loop*. If your program
3477db96d56Sopenharmony_ci  isn't running the event loop, your user interface won't update.
3487db96d56Sopenharmony_ci
3497db96d56Sopenharmony_ci
3507db96d56Sopenharmony_ciUnderstanding How Tkinter Wraps Tcl/Tk
3517db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3527db96d56Sopenharmony_ci
3537db96d56Sopenharmony_ciWhen your application uses Tkinter's classes and methods, internally Tkinter
3547db96d56Sopenharmony_ciis assembling strings representing Tcl/Tk commands, and executing those
3557db96d56Sopenharmony_cicommands in the Tcl interpreter attached to your applicaton's :class:`Tk`
3567db96d56Sopenharmony_ciinstance.
3577db96d56Sopenharmony_ci
3587db96d56Sopenharmony_ciWhether it's trying to navigate reference documentation, trying to find
3597db96d56Sopenharmony_cithe right method or option, adapting some existing code, or debugging your
3607db96d56Sopenharmony_ciTkinter application, there are times that it will be useful to understand
3617db96d56Sopenharmony_ciwhat those underlying Tcl/Tk commands look like.
3627db96d56Sopenharmony_ci
3637db96d56Sopenharmony_ciTo illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter
3647db96d56Sopenharmony_ciscript above.
3657db96d56Sopenharmony_ci
3667db96d56Sopenharmony_ci::
3677db96d56Sopenharmony_ci
3687db96d56Sopenharmony_ci    ttk::frame .frm -padding 10
3697db96d56Sopenharmony_ci    grid .frm
3707db96d56Sopenharmony_ci    grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0
3717db96d56Sopenharmony_ci    grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0
3727db96d56Sopenharmony_ci
3737db96d56Sopenharmony_ci
3747db96d56Sopenharmony_ciTcl's syntax is similar to many shell languages, where the first word is the
3757db96d56Sopenharmony_cicommand to be executed, with arguments to that command following it, separated
3767db96d56Sopenharmony_ciby spaces. Without getting into too many details, notice the following:
3777db96d56Sopenharmony_ci
3787db96d56Sopenharmony_ci* The commands used to create widgets (like ``ttk::frame``) correspond to
3797db96d56Sopenharmony_ci  widget classes in Tkinter.
3807db96d56Sopenharmony_ci
3817db96d56Sopenharmony_ci* Tcl widget options (like ``-text``) correspond to keyword arguments in
3827db96d56Sopenharmony_ci  Tkinter.
3837db96d56Sopenharmony_ci
3847db96d56Sopenharmony_ci* Widgets are referred to by a *pathname* in Tcl (like ``.frm.btn``),
3857db96d56Sopenharmony_ci  whereas Tkinter doesn't use names but object references.
3867db96d56Sopenharmony_ci
3877db96d56Sopenharmony_ci* A widget's place in the widget hierarchy is encoded in its (hierarchical)
3887db96d56Sopenharmony_ci  pathname, which uses a ``.`` (dot) as a path separator. The pathname for
3897db96d56Sopenharmony_ci  the root window is just ``.`` (dot). In Tkinter, the hierarchy is defined
3907db96d56Sopenharmony_ci  not by pathname but by specifying the parent widget when creating each
3917db96d56Sopenharmony_ci  child widget.
3927db96d56Sopenharmony_ci
3937db96d56Sopenharmony_ci* Operations which are implemented as separate *commands* in Tcl (like
3947db96d56Sopenharmony_ci  ``grid`` or ``destroy``) are represented as *methods* on Tkinter widget
3957db96d56Sopenharmony_ci  objects. As you'll see shortly, at other times Tcl uses what appear to be
3967db96d56Sopenharmony_ci  method calls on widget objects, which more closely mirror what would is
3977db96d56Sopenharmony_ci  used in Tkinter.
3987db96d56Sopenharmony_ci
3997db96d56Sopenharmony_ci
4007db96d56Sopenharmony_ciHow do I...? What option does...?
4017db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4027db96d56Sopenharmony_ci
4037db96d56Sopenharmony_ciIf you're not sure how to do something in Tkinter, and you can't immediately
4047db96d56Sopenharmony_cifind it in the tutorial or reference documentation you're using, there are a
4057db96d56Sopenharmony_cifew strategies that can be helpful.
4067db96d56Sopenharmony_ci
4077db96d56Sopenharmony_ciFirst, remember that the details of how individual widgets work may vary
4087db96d56Sopenharmony_ciacross different versions of both Tkinter and Tcl/Tk. If you're searching
4097db96d56Sopenharmony_cidocumentation, make sure it corresponds to the Python and Tcl/Tk versions
4107db96d56Sopenharmony_ciinstalled on your system.
4117db96d56Sopenharmony_ci
4127db96d56Sopenharmony_ciWhen searching for how to use an API, it helps to know the exact name of the
4137db96d56Sopenharmony_ciclass, option, or method that you're using. Introspection, either in an
4147db96d56Sopenharmony_ciinteractive Python shell or with :func:`print`, can help you identify what
4157db96d56Sopenharmony_ciyou need.
4167db96d56Sopenharmony_ci
4177db96d56Sopenharmony_ciTo find out what configuration options are available on any widget, call its
4187db96d56Sopenharmony_ci:meth:`configure` method, which returns a dictionary containing a variety of
4197db96d56Sopenharmony_ciinformation about each object, including its default and current values. Use
4207db96d56Sopenharmony_ci:meth:`keys` to get just the names of each option.
4217db96d56Sopenharmony_ci
4227db96d56Sopenharmony_ci::
4237db96d56Sopenharmony_ci
4247db96d56Sopenharmony_ci    btn = ttk.Button(frm, ...)
4257db96d56Sopenharmony_ci    print(btn.configure().keys())
4267db96d56Sopenharmony_ci
4277db96d56Sopenharmony_ciAs most widgets have many configuration options in common, it can be useful
4287db96d56Sopenharmony_cito find out which are specific to a particular widget class. Comparing the
4297db96d56Sopenharmony_cilist of options to that of a simpler widget, like a frame, is one way to
4307db96d56Sopenharmony_cido that.
4317db96d56Sopenharmony_ci
4327db96d56Sopenharmony_ci::
4337db96d56Sopenharmony_ci
4347db96d56Sopenharmony_ci    print(set(btn.configure().keys()) - set(frm.configure().keys()))
4357db96d56Sopenharmony_ci
4367db96d56Sopenharmony_ciSimilarly, you can find the available methods for a widget object using the
4377db96d56Sopenharmony_cistandard :func:`dir` function. If you try it, you'll see there are over 200
4387db96d56Sopenharmony_cicommon widget methods, so again identifying those specific to a widget class
4397db96d56Sopenharmony_ciis helpful.
4407db96d56Sopenharmony_ci
4417db96d56Sopenharmony_ci::
4427db96d56Sopenharmony_ci
4437db96d56Sopenharmony_ci    print(dir(btn))
4447db96d56Sopenharmony_ci    print(set(dir(btn)) - set(dir(frm)))
4457db96d56Sopenharmony_ci
4467db96d56Sopenharmony_ci
4477db96d56Sopenharmony_ciNavigating the Tcl/Tk Reference Manual
4487db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4497db96d56Sopenharmony_ci
4507db96d56Sopenharmony_ciAs noted, the official `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
4517db96d56Sopenharmony_cireference manual (man pages) is often the most accurate description of what
4527db96d56Sopenharmony_cispecific operations on widgets do. Even when you know the name of the option
4537db96d56Sopenharmony_cior method that you need, you may still have a few places to look.
4547db96d56Sopenharmony_ci
4557db96d56Sopenharmony_ciWhile all operations in Tkinter are implemented as method calls on widget
4567db96d56Sopenharmony_ciobjects, you've seen that many Tcl/Tk operations appear as commands that
4577db96d56Sopenharmony_citake a widget pathname as its first parameter, followed by optional
4587db96d56Sopenharmony_ciparameters, e.g.
4597db96d56Sopenharmony_ci
4607db96d56Sopenharmony_ci::
4617db96d56Sopenharmony_ci
4627db96d56Sopenharmony_ci    destroy .
4637db96d56Sopenharmony_ci    grid .frm.btn -column 0 -row 0
4647db96d56Sopenharmony_ci
4657db96d56Sopenharmony_ciOthers, however, look more like methods called on a widget object (in fact,
4667db96d56Sopenharmony_ciwhen you create a widget in Tcl/Tk, it creates a Tcl command with the name
4677db96d56Sopenharmony_ciof the widget pathname, with the first parameter to that command being the
4687db96d56Sopenharmony_ciname of a method to call).
4697db96d56Sopenharmony_ci
4707db96d56Sopenharmony_ci::
4717db96d56Sopenharmony_ci
4727db96d56Sopenharmony_ci    .frm.btn invoke
4737db96d56Sopenharmony_ci    .frm.lbl configure -text "Goodbye"
4747db96d56Sopenharmony_ci
4757db96d56Sopenharmony_ci
4767db96d56Sopenharmony_ciIn the official Tcl/Tk reference documentation, you'll find most operations
4777db96d56Sopenharmony_cithat look like method calls on the man page for a specific widget (e.g.,
4787db96d56Sopenharmony_ciyou'll find the :meth:`invoke` method on the
4797db96d56Sopenharmony_ci`ttk::button <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_button.htm>`_
4807db96d56Sopenharmony_ciman page), while functions that take a widget as a parameter often have
4817db96d56Sopenharmony_citheir own man page (e.g.,
4827db96d56Sopenharmony_ci`grid <https://www.tcl.tk/man/tcl8.6/TkCmd/grid.htm>`_).
4837db96d56Sopenharmony_ci
4847db96d56Sopenharmony_ciYou'll find many common options and methods in the
4857db96d56Sopenharmony_ci`options <https://www.tcl.tk/man/tcl8.6/TkCmd/options.htm>`_ or
4867db96d56Sopenharmony_ci`ttk::widget <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_widget.htm>`_ man
4877db96d56Sopenharmony_cipages, while others are found in the man page for a specific widget class.
4887db96d56Sopenharmony_ci
4897db96d56Sopenharmony_ciYou'll also find that many Tkinter methods have compound names, e.g.,
4907db96d56Sopenharmony_ci:func:`winfo_x`, :func:`winfo_height`, :func:`winfo_viewable`. You'd find
4917db96d56Sopenharmony_cidocumentation for all of these in the
4927db96d56Sopenharmony_ci`winfo <https://www.tcl.tk/man/tcl8.6/TkCmd/winfo.htm>`_ man page.
4937db96d56Sopenharmony_ci
4947db96d56Sopenharmony_ci.. note::
4957db96d56Sopenharmony_ci   Somewhat confusingly, there are also methods on all Tkinter widgets
4967db96d56Sopenharmony_ci   that don't actually operate on the widget, but operate at a global
4977db96d56Sopenharmony_ci   scope, independent of any widget. Examples are methods for accessing
4987db96d56Sopenharmony_ci   the clipboard or the system bell. (They happen to be implemented as
4997db96d56Sopenharmony_ci   methods in the base :class:`Widget` class that all Tkinter widgets
5007db96d56Sopenharmony_ci   inherit from).
5017db96d56Sopenharmony_ci
5027db96d56Sopenharmony_ci
5037db96d56Sopenharmony_ciThreading model
5047db96d56Sopenharmony_ci---------------
5057db96d56Sopenharmony_ci
5067db96d56Sopenharmony_ciPython and Tcl/Tk have very different threading models, which :mod:`tkinter`
5077db96d56Sopenharmony_citries to bridge. If you use threads, you may need to be aware of this.
5087db96d56Sopenharmony_ci
5097db96d56Sopenharmony_ciA Python interpreter may have many threads associated with it. In Tcl, multiple
5107db96d56Sopenharmony_cithreads can be created, but each thread has a separate Tcl interpreter instance
5117db96d56Sopenharmony_ciassociated with it. Threads can also create more than one interpreter instance,
5127db96d56Sopenharmony_cithough each interpreter instance can be used only by the one thread that created it.
5137db96d56Sopenharmony_ci
5147db96d56Sopenharmony_ciEach :class:`Tk` object created by :mod:`tkinter` contains a Tcl interpreter.
5157db96d56Sopenharmony_ciIt also keeps track of which thread created that interpreter. Calls to
5167db96d56Sopenharmony_ci:mod:`tkinter` can be made from any Python thread. Internally, if a call comes
5177db96d56Sopenharmony_cifrom a thread other than the one that created the :class:`Tk` object, an event
5187db96d56Sopenharmony_ciis posted to the interpreter's event queue, and when executed, the result is
5197db96d56Sopenharmony_cireturned to the calling Python thread.
5207db96d56Sopenharmony_ci
5217db96d56Sopenharmony_ciTcl/Tk applications are normally event-driven, meaning that after initialization,
5227db96d56Sopenharmony_cithe interpreter runs an event loop (i.e. :func:`Tk.mainloop`) and responds to events.
5237db96d56Sopenharmony_ciBecause it is single-threaded, event handlers must respond quickly, otherwise they
5247db96d56Sopenharmony_ciwill block other events from being processed. To avoid this, any long-running
5257db96d56Sopenharmony_cicomputations should not run in an event handler, but are either broken into smaller
5267db96d56Sopenharmony_cipieces using timers, or run in another thread. This is different from many GUI
5277db96d56Sopenharmony_citoolkits where the GUI runs in a completely separate thread from all application
5287db96d56Sopenharmony_cicode including event handlers.
5297db96d56Sopenharmony_ci
5307db96d56Sopenharmony_ciIf the Tcl interpreter is not running the event loop and processing events, any
5317db96d56Sopenharmony_ci:mod:`tkinter` calls made from threads other than the one running the Tcl
5327db96d56Sopenharmony_ciinterpreter will fail.
5337db96d56Sopenharmony_ci
5347db96d56Sopenharmony_ciA number of special cases exist:
5357db96d56Sopenharmony_ci
5367db96d56Sopenharmony_ci  * Tcl/Tk libraries can be built so they are not thread-aware. In this case,
5377db96d56Sopenharmony_ci    :mod:`tkinter` calls the library from the originating Python thread, even
5387db96d56Sopenharmony_ci    if this is different than the thread that created the Tcl interpreter. A global
5397db96d56Sopenharmony_ci    lock ensures only one call occurs at a time.
5407db96d56Sopenharmony_ci
5417db96d56Sopenharmony_ci  * While :mod:`tkinter` allows you to create more than one instance of a :class:`Tk`
5427db96d56Sopenharmony_ci    object (with its own interpreter), all interpreters that are part of the same
5437db96d56Sopenharmony_ci    thread share a common event queue, which gets ugly fast. In practice, don't create
5447db96d56Sopenharmony_ci    more than one instance of :class:`Tk` at a time. Otherwise, it's best to create
5457db96d56Sopenharmony_ci    them in separate threads and ensure you're running a thread-aware Tcl/Tk build.
5467db96d56Sopenharmony_ci
5477db96d56Sopenharmony_ci  * Blocking event handlers are not the only way to prevent the Tcl interpreter from
5487db96d56Sopenharmony_ci    reentering the event loop. It is even possible to run multiple nested event loops
5497db96d56Sopenharmony_ci    or abandon the event loop entirely. If you're doing anything tricky when it comes
5507db96d56Sopenharmony_ci    to events or threads, be aware of these possibilities.
5517db96d56Sopenharmony_ci
5527db96d56Sopenharmony_ci  * There are a few select :mod:`tkinter` functions that presently work only when
5537db96d56Sopenharmony_ci    called from the thread that created the Tcl interpreter.
5547db96d56Sopenharmony_ci
5557db96d56Sopenharmony_ci
5567db96d56Sopenharmony_ciHandy Reference
5577db96d56Sopenharmony_ci---------------
5587db96d56Sopenharmony_ci
5597db96d56Sopenharmony_ci
5607db96d56Sopenharmony_ci.. _tkinter-setting-options:
5617db96d56Sopenharmony_ci
5627db96d56Sopenharmony_ciSetting Options
5637db96d56Sopenharmony_ci^^^^^^^^^^^^^^^
5647db96d56Sopenharmony_ci
5657db96d56Sopenharmony_ciOptions control things like the color and border width of a widget. Options can
5667db96d56Sopenharmony_cibe set in three ways:
5677db96d56Sopenharmony_ci
5687db96d56Sopenharmony_ciAt object creation time, using keyword arguments
5697db96d56Sopenharmony_ci   ::
5707db96d56Sopenharmony_ci
5717db96d56Sopenharmony_ci      fred = Button(self, fg="red", bg="blue")
5727db96d56Sopenharmony_ci
5737db96d56Sopenharmony_ciAfter object creation, treating the option name like a dictionary index
5747db96d56Sopenharmony_ci   ::
5757db96d56Sopenharmony_ci
5767db96d56Sopenharmony_ci      fred["fg"] = "red"
5777db96d56Sopenharmony_ci      fred["bg"] = "blue"
5787db96d56Sopenharmony_ci
5797db96d56Sopenharmony_ciUse the config() method to update multiple attrs subsequent to object creation
5807db96d56Sopenharmony_ci   ::
5817db96d56Sopenharmony_ci
5827db96d56Sopenharmony_ci      fred.config(fg="red", bg="blue")
5837db96d56Sopenharmony_ci
5847db96d56Sopenharmony_ciFor a complete explanation of a given option and its behavior, see the Tk man
5857db96d56Sopenharmony_cipages for the widget in question.
5867db96d56Sopenharmony_ci
5877db96d56Sopenharmony_ciNote that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
5887db96d56Sopenharmony_cifor each widget.  The former is a list of options that are common to many
5897db96d56Sopenharmony_ciwidgets, the latter are the options that are idiosyncratic to that particular
5907db96d56Sopenharmony_ciwidget.  The Standard Options are documented on the :manpage:`options(3)` man
5917db96d56Sopenharmony_cipage.
5927db96d56Sopenharmony_ci
5937db96d56Sopenharmony_ciNo distinction between standard and widget-specific options is made in this
5947db96d56Sopenharmony_cidocument.  Some options don't apply to some kinds of widgets. Whether a given
5957db96d56Sopenharmony_ciwidget responds to a particular option depends on the class of the widget;
5967db96d56Sopenharmony_cibuttons have a ``command`` option, labels do not.
5977db96d56Sopenharmony_ci
5987db96d56Sopenharmony_ciThe options supported by a given widget are listed in that widget's man page, or
5997db96d56Sopenharmony_cican be queried at runtime by calling the :meth:`config` method without
6007db96d56Sopenharmony_ciarguments, or by calling the :meth:`keys` method on that widget.  The return
6017db96d56Sopenharmony_civalue of these calls is a dictionary whose key is the name of the option as a
6027db96d56Sopenharmony_cistring (for example, ``'relief'``) and whose values are 5-tuples.
6037db96d56Sopenharmony_ci
6047db96d56Sopenharmony_ciSome options, like ``bg`` are synonyms for common options with long names
6057db96d56Sopenharmony_ci(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
6067db96d56Sopenharmony_ciof a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
6077db96d56Sopenharmony_ciback will contain the name of the synonym and the "real" option (such as
6087db96d56Sopenharmony_ci``('bg', 'background')``).
6097db96d56Sopenharmony_ci
6107db96d56Sopenharmony_ci+-------+---------------------------------+--------------+
6117db96d56Sopenharmony_ci| Index | Meaning                         | Example      |
6127db96d56Sopenharmony_ci+=======+=================================+==============+
6137db96d56Sopenharmony_ci| 0     | option name                     | ``'relief'`` |
6147db96d56Sopenharmony_ci+-------+---------------------------------+--------------+
6157db96d56Sopenharmony_ci| 1     | option name for database lookup | ``'relief'`` |
6167db96d56Sopenharmony_ci+-------+---------------------------------+--------------+
6177db96d56Sopenharmony_ci| 2     | option class for database       | ``'Relief'`` |
6187db96d56Sopenharmony_ci|       | lookup                          |              |
6197db96d56Sopenharmony_ci+-------+---------------------------------+--------------+
6207db96d56Sopenharmony_ci| 3     | default value                   | ``'raised'`` |
6217db96d56Sopenharmony_ci+-------+---------------------------------+--------------+
6227db96d56Sopenharmony_ci| 4     | current value                   | ``'groove'`` |
6237db96d56Sopenharmony_ci+-------+---------------------------------+--------------+
6247db96d56Sopenharmony_ci
6257db96d56Sopenharmony_ciExample::
6267db96d56Sopenharmony_ci
6277db96d56Sopenharmony_ci   >>> print(fred.config())
6287db96d56Sopenharmony_ci   {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}
6297db96d56Sopenharmony_ci
6307db96d56Sopenharmony_ciOf course, the dictionary printed will include all the options available and
6317db96d56Sopenharmony_citheir values.  This is meant only as an example.
6327db96d56Sopenharmony_ci
6337db96d56Sopenharmony_ci
6347db96d56Sopenharmony_ciThe Packer
6357db96d56Sopenharmony_ci^^^^^^^^^^
6367db96d56Sopenharmony_ci
6377db96d56Sopenharmony_ci.. index:: single: packing (widgets)
6387db96d56Sopenharmony_ci
6397db96d56Sopenharmony_ciThe packer is one of Tk's geometry-management mechanisms.    Geometry managers
6407db96d56Sopenharmony_ciare used to specify the relative positioning of widgets within their container -
6417db96d56Sopenharmony_citheir mutual *master*.  In contrast to the more cumbersome *placer* (which is
6427db96d56Sopenharmony_ciused less commonly, and we do not cover here), the packer takes qualitative
6437db96d56Sopenharmony_cirelationship specification - *above*, *to the left of*, *filling*, etc - and
6447db96d56Sopenharmony_ciworks everything out to determine the exact placement coordinates for you.
6457db96d56Sopenharmony_ci
6467db96d56Sopenharmony_ciThe size of any *master* widget is determined by the size of the "slave widgets"
6477db96d56Sopenharmony_ciinside.  The packer is used to control where slave widgets appear inside the
6487db96d56Sopenharmony_cimaster into which they are packed.  You can pack widgets into frames, and frames
6497db96d56Sopenharmony_ciinto other frames, in order to achieve the kind of layout you desire.
6507db96d56Sopenharmony_ciAdditionally, the arrangement is dynamically adjusted to accommodate incremental
6517db96d56Sopenharmony_cichanges to the configuration, once it is packed.
6527db96d56Sopenharmony_ci
6537db96d56Sopenharmony_ciNote that widgets do not appear until they have had their geometry specified
6547db96d56Sopenharmony_ciwith a geometry manager.  It's a common early mistake to leave out the geometry
6557db96d56Sopenharmony_cispecification, and then be surprised when the widget is created but nothing
6567db96d56Sopenharmony_ciappears.  A widget will appear only after it has had, for example, the packer's
6577db96d56Sopenharmony_ci:meth:`pack` method applied to it.
6587db96d56Sopenharmony_ci
6597db96d56Sopenharmony_ciThe pack() method can be called with keyword-option/value pairs that control
6607db96d56Sopenharmony_ciwhere the widget is to appear within its container, and how it is to behave when
6617db96d56Sopenharmony_cithe main application window is resized.  Here are some examples::
6627db96d56Sopenharmony_ci
6637db96d56Sopenharmony_ci   fred.pack()                     # defaults to side = "top"
6647db96d56Sopenharmony_ci   fred.pack(side="left")
6657db96d56Sopenharmony_ci   fred.pack(expand=1)
6667db96d56Sopenharmony_ci
6677db96d56Sopenharmony_ci
6687db96d56Sopenharmony_ciPacker Options
6697db96d56Sopenharmony_ci^^^^^^^^^^^^^^
6707db96d56Sopenharmony_ci
6717db96d56Sopenharmony_ciFor more extensive information on the packer and the options that it can take,
6727db96d56Sopenharmony_cisee the man pages and page 183 of John Ousterhout's book.
6737db96d56Sopenharmony_ci
6747db96d56Sopenharmony_cianchor
6757db96d56Sopenharmony_ci   Anchor type.  Denotes where the packer is to place each slave in its parcel.
6767db96d56Sopenharmony_ci
6777db96d56Sopenharmony_ciexpand
6787db96d56Sopenharmony_ci   Boolean, ``0`` or ``1``.
6797db96d56Sopenharmony_ci
6807db96d56Sopenharmony_cifill
6817db96d56Sopenharmony_ci   Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
6827db96d56Sopenharmony_ci
6837db96d56Sopenharmony_ciipadx and ipady
6847db96d56Sopenharmony_ci   A distance - designating internal padding on each side of the slave widget.
6857db96d56Sopenharmony_ci
6867db96d56Sopenharmony_cipadx and pady
6877db96d56Sopenharmony_ci   A distance - designating external padding on each side of the slave widget.
6887db96d56Sopenharmony_ci
6897db96d56Sopenharmony_ciside
6907db96d56Sopenharmony_ci   Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
6917db96d56Sopenharmony_ci
6927db96d56Sopenharmony_ci
6937db96d56Sopenharmony_ciCoupling Widget Variables
6947db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^^^^^^
6957db96d56Sopenharmony_ci
6967db96d56Sopenharmony_ciThe current-value setting of some widgets (like text entry widgets) can be
6977db96d56Sopenharmony_ciconnected directly to application variables by using special options.  These
6987db96d56Sopenharmony_cioptions are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
6997db96d56Sopenharmony_ci``value``.  This connection works both ways: if the variable changes for any
7007db96d56Sopenharmony_cireason, the widget it's connected to will be updated to reflect the new value.
7017db96d56Sopenharmony_ci
7027db96d56Sopenharmony_ciUnfortunately, in the current implementation of :mod:`tkinter` it is not
7037db96d56Sopenharmony_cipossible to hand over an arbitrary Python variable to a widget through a
7047db96d56Sopenharmony_ci``variable`` or ``textvariable`` option.  The only kinds of variables for which
7057db96d56Sopenharmony_cithis works are variables that are subclassed from a class called Variable,
7067db96d56Sopenharmony_cidefined in :mod:`tkinter`.
7077db96d56Sopenharmony_ci
7087db96d56Sopenharmony_ciThere are many useful subclasses of Variable already defined:
7097db96d56Sopenharmony_ci:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
7107db96d56Sopenharmony_ci:class:`BooleanVar`.  To read the current value of such a variable, call the
7117db96d56Sopenharmony_ci:meth:`get` method on it, and to change its value you call the :meth:`!set`
7127db96d56Sopenharmony_cimethod.  If you follow this protocol, the widget will always track the value of
7137db96d56Sopenharmony_cithe variable, with no further intervention on your part.
7147db96d56Sopenharmony_ci
7157db96d56Sopenharmony_ciFor example::
7167db96d56Sopenharmony_ci
7177db96d56Sopenharmony_ci   import tkinter as tk
7187db96d56Sopenharmony_ci
7197db96d56Sopenharmony_ci   class App(tk.Frame):
7207db96d56Sopenharmony_ci       def __init__(self, master):
7217db96d56Sopenharmony_ci           super().__init__(master)
7227db96d56Sopenharmony_ci           self.pack()
7237db96d56Sopenharmony_ci
7247db96d56Sopenharmony_ci           self.entrythingy = tk.Entry()
7257db96d56Sopenharmony_ci           self.entrythingy.pack()
7267db96d56Sopenharmony_ci
7277db96d56Sopenharmony_ci           # Create the application variable.
7287db96d56Sopenharmony_ci           self.contents = tk.StringVar()
7297db96d56Sopenharmony_ci           # Set it to some value.
7307db96d56Sopenharmony_ci           self.contents.set("this is a variable")
7317db96d56Sopenharmony_ci           # Tell the entry widget to watch this variable.
7327db96d56Sopenharmony_ci           self.entrythingy["textvariable"] = self.contents
7337db96d56Sopenharmony_ci
7347db96d56Sopenharmony_ci           # Define a callback for when the user hits return.
7357db96d56Sopenharmony_ci           # It prints the current value of the variable.
7367db96d56Sopenharmony_ci           self.entrythingy.bind('<Key-Return>',
7377db96d56Sopenharmony_ci                                self.print_contents)
7387db96d56Sopenharmony_ci
7397db96d56Sopenharmony_ci       def print_contents(self, event):
7407db96d56Sopenharmony_ci           print("Hi. The current entry content is:",
7417db96d56Sopenharmony_ci                 self.contents.get())
7427db96d56Sopenharmony_ci
7437db96d56Sopenharmony_ci   root = tk.Tk()
7447db96d56Sopenharmony_ci   myapp = App(root)
7457db96d56Sopenharmony_ci   myapp.mainloop()
7467db96d56Sopenharmony_ci
7477db96d56Sopenharmony_ciThe Window Manager
7487db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^
7497db96d56Sopenharmony_ci
7507db96d56Sopenharmony_ci.. index:: single: window manager (widgets)
7517db96d56Sopenharmony_ci
7527db96d56Sopenharmony_ciIn Tk, there is a utility command, ``wm``, for interacting with the window
7537db96d56Sopenharmony_cimanager.  Options to the ``wm`` command allow you to control things like titles,
7547db96d56Sopenharmony_ciplacement, icon bitmaps, and the like.  In :mod:`tkinter`, these commands have
7557db96d56Sopenharmony_cibeen implemented as methods on the :class:`Wm` class.  Toplevel widgets are
7567db96d56Sopenharmony_cisubclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
7577db96d56Sopenharmony_cidirectly.
7587db96d56Sopenharmony_ci
7597db96d56Sopenharmony_ciTo get at the toplevel window that contains a given widget, you can often just
7607db96d56Sopenharmony_cirefer to the widget's master.  Of course if the widget has been packed inside of
7617db96d56Sopenharmony_cia frame, the master won't represent a toplevel window.  To get at the toplevel
7627db96d56Sopenharmony_ciwindow that contains an arbitrary widget, you can call the :meth:`_root` method.
7637db96d56Sopenharmony_ciThis method begins with an underscore to denote the fact that this function is
7647db96d56Sopenharmony_cipart of the implementation, and not an interface to Tk functionality.
7657db96d56Sopenharmony_ci
7667db96d56Sopenharmony_ciHere are some examples of typical usage::
7677db96d56Sopenharmony_ci
7687db96d56Sopenharmony_ci   import tkinter as tk
7697db96d56Sopenharmony_ci
7707db96d56Sopenharmony_ci   class App(tk.Frame):
7717db96d56Sopenharmony_ci       def __init__(self, master=None):
7727db96d56Sopenharmony_ci           super().__init__(master)
7737db96d56Sopenharmony_ci           self.pack()
7747db96d56Sopenharmony_ci
7757db96d56Sopenharmony_ci   # create the application
7767db96d56Sopenharmony_ci   myapp = App()
7777db96d56Sopenharmony_ci
7787db96d56Sopenharmony_ci   #
7797db96d56Sopenharmony_ci   # here are method calls to the window manager class
7807db96d56Sopenharmony_ci   #
7817db96d56Sopenharmony_ci   myapp.master.title("My Do-Nothing Application")
7827db96d56Sopenharmony_ci   myapp.master.maxsize(1000, 400)
7837db96d56Sopenharmony_ci
7847db96d56Sopenharmony_ci   # start the program
7857db96d56Sopenharmony_ci   myapp.mainloop()
7867db96d56Sopenharmony_ci
7877db96d56Sopenharmony_ci
7887db96d56Sopenharmony_ciTk Option Data Types
7897db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^^
7907db96d56Sopenharmony_ci
7917db96d56Sopenharmony_ci.. index:: single: Tk Option Data Types
7927db96d56Sopenharmony_ci
7937db96d56Sopenharmony_cianchor
7947db96d56Sopenharmony_ci   Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
7957db96d56Sopenharmony_ci   ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
7967db96d56Sopenharmony_ci
7977db96d56Sopenharmony_cibitmap
7987db96d56Sopenharmony_ci   There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
7997db96d56Sopenharmony_ci   ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
8007db96d56Sopenharmony_ci   ``'warning'``.  To specify an X bitmap filename, give the full path to the file,
8017db96d56Sopenharmony_ci   preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
8027db96d56Sopenharmony_ci
8037db96d56Sopenharmony_ciboolean
8047db96d56Sopenharmony_ci   You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.
8057db96d56Sopenharmony_ci
8067db96d56Sopenharmony_cicallback
8077db96d56Sopenharmony_ci   This is any Python function that takes no arguments.  For example::
8087db96d56Sopenharmony_ci
8097db96d56Sopenharmony_ci      def print_it():
8107db96d56Sopenharmony_ci          print("hi there")
8117db96d56Sopenharmony_ci      fred["command"] = print_it
8127db96d56Sopenharmony_ci
8137db96d56Sopenharmony_cicolor
8147db96d56Sopenharmony_ci   Colors can be given as the names of X colors in the rgb.txt file, or as strings
8157db96d56Sopenharmony_ci   representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit:
8167db96d56Sopenharmony_ci   ``"#RRRGGGBBB"``, or 16 bit: ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
8177db96d56Sopenharmony_ci   represent any legal hex digit.  See page 160 of Ousterhout's book for details.
8187db96d56Sopenharmony_ci
8197db96d56Sopenharmony_cicursor
8207db96d56Sopenharmony_ci   The standard X cursor names from :file:`cursorfont.h` can be used, without the
8217db96d56Sopenharmony_ci   ``XC_`` prefix.  For example to get a hand cursor (:const:`XC_hand2`), use the
8227db96d56Sopenharmony_ci   string ``"hand2"``.  You can also specify a bitmap and mask file of your own.
8237db96d56Sopenharmony_ci   See page 179 of Ousterhout's book.
8247db96d56Sopenharmony_ci
8257db96d56Sopenharmony_cidistance
8267db96d56Sopenharmony_ci   Screen distances can be specified in either pixels or absolute distances.
8277db96d56Sopenharmony_ci   Pixels are given as numbers and absolute distances as strings, with the trailing
8287db96d56Sopenharmony_ci   character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
8297db96d56Sopenharmony_ci   millimetres, ``p`` for printer's points.  For example, 3.5 inches is expressed
8307db96d56Sopenharmony_ci   as ``"3.5i"``.
8317db96d56Sopenharmony_ci
8327db96d56Sopenharmony_cifont
8337db96d56Sopenharmony_ci   Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
8347db96d56Sopenharmony_ci   positive numbers are measured in points; sizes with negative numbers are
8357db96d56Sopenharmony_ci   measured in pixels.
8367db96d56Sopenharmony_ci
8377db96d56Sopenharmony_cigeometry
8387db96d56Sopenharmony_ci   This is a string of the form ``widthxheight``, where width and height are
8397db96d56Sopenharmony_ci   measured in pixels for most widgets (in characters for widgets displaying text).
8407db96d56Sopenharmony_ci   For example: ``fred["geometry"] = "200x100"``.
8417db96d56Sopenharmony_ci
8427db96d56Sopenharmony_cijustify
8437db96d56Sopenharmony_ci   Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
8447db96d56Sopenharmony_ci   ``"fill"``.
8457db96d56Sopenharmony_ci
8467db96d56Sopenharmony_ciregion
8477db96d56Sopenharmony_ci   This is a string with four space-delimited elements, each of which is a legal
8487db96d56Sopenharmony_ci   distance (see above).  For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
8497db96d56Sopenharmony_ci   ``"3c 2c 4c 10.43c"``  are all legal regions.
8507db96d56Sopenharmony_ci
8517db96d56Sopenharmony_cirelief
8527db96d56Sopenharmony_ci   Determines what the border style of a widget will be.  Legal values are:
8537db96d56Sopenharmony_ci   ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
8547db96d56Sopenharmony_ci
8557db96d56Sopenharmony_ciscrollcommand
8567db96d56Sopenharmony_ci   This is almost always the :meth:`!set` method of some scrollbar widget, but can
8577db96d56Sopenharmony_ci   be any widget method that takes a single argument.
8587db96d56Sopenharmony_ci
8597db96d56Sopenharmony_ciwrap
8607db96d56Sopenharmony_ci   Must be one of: ``"none"``, ``"char"``, or ``"word"``.
8617db96d56Sopenharmony_ci
8627db96d56Sopenharmony_ci.. _Bindings-and-Events:
8637db96d56Sopenharmony_ci
8647db96d56Sopenharmony_ciBindings and Events
8657db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^
8667db96d56Sopenharmony_ci
8677db96d56Sopenharmony_ci.. index::
8687db96d56Sopenharmony_ci   single: bind (widgets)
8697db96d56Sopenharmony_ci   single: events (widgets)
8707db96d56Sopenharmony_ci
8717db96d56Sopenharmony_ciThe bind method from the widget command allows you to watch for certain events
8727db96d56Sopenharmony_ciand to have a callback function trigger when that event type occurs.  The form
8737db96d56Sopenharmony_ciof the bind method is::
8747db96d56Sopenharmony_ci
8757db96d56Sopenharmony_ci   def bind(self, sequence, func, add=''):
8767db96d56Sopenharmony_ci
8777db96d56Sopenharmony_ciwhere:
8787db96d56Sopenharmony_ci
8797db96d56Sopenharmony_cisequence
8807db96d56Sopenharmony_ci   is a string that denotes the target kind of event.  (See the
8817db96d56Sopenharmony_ci   :manpage:`bind(3tk)` man page, and page 201 of John Ousterhout's book,
8827db96d56Sopenharmony_ci   :title-reference:`Tcl and the Tk Toolkit (2nd edition)`, for details).
8837db96d56Sopenharmony_ci
8847db96d56Sopenharmony_cifunc
8857db96d56Sopenharmony_ci   is a Python function, taking one argument, to be invoked when the event occurs.
8867db96d56Sopenharmony_ci   An Event instance will be passed as the argument. (Functions deployed this way
8877db96d56Sopenharmony_ci   are commonly known as *callbacks*.)
8887db96d56Sopenharmony_ci
8897db96d56Sopenharmony_ciadd
8907db96d56Sopenharmony_ci   is optional, either ``''`` or ``'+'``.  Passing an empty string denotes that
8917db96d56Sopenharmony_ci   this binding is to replace any other bindings that this event is associated
8927db96d56Sopenharmony_ci   with.  Passing a ``'+'`` means that this function is to be added to the list
8937db96d56Sopenharmony_ci   of functions bound to this event type.
8947db96d56Sopenharmony_ci
8957db96d56Sopenharmony_ciFor example::
8967db96d56Sopenharmony_ci
8977db96d56Sopenharmony_ci   def turn_red(self, event):
8987db96d56Sopenharmony_ci       event.widget["activeforeground"] = "red"
8997db96d56Sopenharmony_ci
9007db96d56Sopenharmony_ci   self.button.bind("<Enter>", self.turn_red)
9017db96d56Sopenharmony_ci
9027db96d56Sopenharmony_ciNotice how the widget field of the event is being accessed in the
9037db96d56Sopenharmony_ci``turn_red()`` callback.  This field contains the widget that caught the X
9047db96d56Sopenharmony_cievent.  The following table lists the other event fields you can access, and how
9057db96d56Sopenharmony_cithey are denoted in Tk, which can be useful when referring to the Tk man pages.
9067db96d56Sopenharmony_ci
9077db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9087db96d56Sopenharmony_ci| Tk | Tkinter Event Field | Tk | Tkinter Event Field |
9097db96d56Sopenharmony_ci+====+=====================+====+=====================+
9107db96d56Sopenharmony_ci| %f | focus               | %A | char                |
9117db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9127db96d56Sopenharmony_ci| %h | height              | %E | send_event          |
9137db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9147db96d56Sopenharmony_ci| %k | keycode             | %K | keysym              |
9157db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9167db96d56Sopenharmony_ci| %s | state               | %N | keysym_num          |
9177db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9187db96d56Sopenharmony_ci| %t | time                | %T | type                |
9197db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9207db96d56Sopenharmony_ci| %w | width               | %W | widget              |
9217db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9227db96d56Sopenharmony_ci| %x | x                   | %X | x_root              |
9237db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9247db96d56Sopenharmony_ci| %y | y                   | %Y | y_root              |
9257db96d56Sopenharmony_ci+----+---------------------+----+---------------------+
9267db96d56Sopenharmony_ci
9277db96d56Sopenharmony_ci
9287db96d56Sopenharmony_ciThe index Parameter
9297db96d56Sopenharmony_ci^^^^^^^^^^^^^^^^^^^
9307db96d56Sopenharmony_ci
9317db96d56Sopenharmony_ciA number of widgets require "index" parameters to be passed.  These are used to
9327db96d56Sopenharmony_cipoint at a specific place in a Text widget, or to particular characters in an
9337db96d56Sopenharmony_ciEntry widget, or to particular menu items in a Menu widget.
9347db96d56Sopenharmony_ci
9357db96d56Sopenharmony_ciEntry widget indexes (index, view index, etc.)
9367db96d56Sopenharmony_ci   Entry widgets have options that refer to character positions in the text being
9377db96d56Sopenharmony_ci   displayed.  You can use these :mod:`tkinter` functions to access these special
9387db96d56Sopenharmony_ci   points in text widgets:
9397db96d56Sopenharmony_ci
9407db96d56Sopenharmony_ciText widget indexes
9417db96d56Sopenharmony_ci   The index notation for Text widgets is very rich and is best described in the Tk
9427db96d56Sopenharmony_ci   man pages.
9437db96d56Sopenharmony_ci
9447db96d56Sopenharmony_ciMenu indexes (menu.invoke(), menu.entryconfig(), etc.)
9457db96d56Sopenharmony_ci   Some options and methods for menus manipulate specific menu entries. Anytime a
9467db96d56Sopenharmony_ci   menu index is needed for an option or a parameter, you may pass in:
9477db96d56Sopenharmony_ci
9487db96d56Sopenharmony_ci   * an integer which refers to the numeric position of the entry in the widget,
9497db96d56Sopenharmony_ci     counted from the top, starting with 0;
9507db96d56Sopenharmony_ci
9517db96d56Sopenharmony_ci   * the string ``"active"``, which refers to the menu position that is currently
9527db96d56Sopenharmony_ci     under the cursor;
9537db96d56Sopenharmony_ci
9547db96d56Sopenharmony_ci   * the string ``"last"`` which refers to the last menu item;
9557db96d56Sopenharmony_ci
9567db96d56Sopenharmony_ci   * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
9577db96d56Sopenharmony_ci     as a y pixel coordinate in the menu's coordinate system;
9587db96d56Sopenharmony_ci
9597db96d56Sopenharmony_ci   * the string ``"none"``, which indicates no menu entry at all, most often used
9607db96d56Sopenharmony_ci     with menu.activate() to deactivate all entries, and finally,
9617db96d56Sopenharmony_ci
9627db96d56Sopenharmony_ci   * a text string that is pattern matched against the label of the menu entry, as
9637db96d56Sopenharmony_ci     scanned from the top of the menu to the bottom.  Note that this index type is
9647db96d56Sopenharmony_ci     considered after all the others, which means that matches for menu items
9657db96d56Sopenharmony_ci     labelled ``last``, ``active``, or ``none`` may be interpreted as the above
9667db96d56Sopenharmony_ci     literals, instead.
9677db96d56Sopenharmony_ci
9687db96d56Sopenharmony_ci
9697db96d56Sopenharmony_ciImages
9707db96d56Sopenharmony_ci^^^^^^
9717db96d56Sopenharmony_ci
9727db96d56Sopenharmony_ciImages of different formats can be created through the corresponding subclass
9737db96d56Sopenharmony_ciof :class:`tkinter.Image`:
9747db96d56Sopenharmony_ci
9757db96d56Sopenharmony_ci* :class:`BitmapImage` for images in XBM format.
9767db96d56Sopenharmony_ci
9777db96d56Sopenharmony_ci* :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter
9787db96d56Sopenharmony_ci  is supported starting with Tk 8.6.
9797db96d56Sopenharmony_ci
9807db96d56Sopenharmony_ciEither type of image is created through either the ``file`` or the ``data``
9817db96d56Sopenharmony_cioption (other options are available as well).
9827db96d56Sopenharmony_ci
9837db96d56Sopenharmony_ciThe image object can then be used wherever an ``image`` option is supported by
9847db96d56Sopenharmony_cisome widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
9857db96d56Sopenharmony_cireference to the image. When the last Python reference to the image object is
9867db96d56Sopenharmony_cideleted, the image data is deleted as well, and Tk will display an empty box
9877db96d56Sopenharmony_ciwherever the image was used.
9887db96d56Sopenharmony_ci
9897db96d56Sopenharmony_ci.. seealso::
9907db96d56Sopenharmony_ci
9917db96d56Sopenharmony_ci    The `Pillow <https://python-pillow.org/>`_ package adds support for
9927db96d56Sopenharmony_ci    formats such as BMP, JPEG, TIFF, and WebP, among others.
9937db96d56Sopenharmony_ci
9947db96d56Sopenharmony_ci.. _tkinter-file-handlers:
9957db96d56Sopenharmony_ci
9967db96d56Sopenharmony_ciFile Handlers
9977db96d56Sopenharmony_ci-------------
9987db96d56Sopenharmony_ci
9997db96d56Sopenharmony_ciTk allows you to register and unregister a callback function which will be
10007db96d56Sopenharmony_cicalled from the Tk mainloop when I/O is possible on a file descriptor.
10017db96d56Sopenharmony_ciOnly one handler may be registered per file descriptor. Example code::
10027db96d56Sopenharmony_ci
10037db96d56Sopenharmony_ci   import tkinter
10047db96d56Sopenharmony_ci   widget = tkinter.Tk()
10057db96d56Sopenharmony_ci   mask = tkinter.READABLE | tkinter.WRITABLE
10067db96d56Sopenharmony_ci   widget.tk.createfilehandler(file, mask, callback)
10077db96d56Sopenharmony_ci   ...
10087db96d56Sopenharmony_ci   widget.tk.deletefilehandler(file)
10097db96d56Sopenharmony_ci
10107db96d56Sopenharmony_ciThis feature is not available on Windows.
10117db96d56Sopenharmony_ci
10127db96d56Sopenharmony_ciSince you don't know how many bytes are available for reading, you may not
10137db96d56Sopenharmony_ciwant to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
10147db96d56Sopenharmony_ci:meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods,
10157db96d56Sopenharmony_cisince these will insist on reading a predefined number of bytes.
10167db96d56Sopenharmony_ciFor sockets, the :meth:`~socket.socket.recv` or
10177db96d56Sopenharmony_ci:meth:`~socket.socket.recvfrom` methods will work fine; for other files,
10187db96d56Sopenharmony_ciuse raw reads or ``os.read(file.fileno(), maxbytecount)``.
10197db96d56Sopenharmony_ci
10207db96d56Sopenharmony_ci
10217db96d56Sopenharmony_ci.. method:: Widget.tk.createfilehandler(file, mask, func)
10227db96d56Sopenharmony_ci
10237db96d56Sopenharmony_ci   Registers the file handler callback function *func*. The *file* argument
10247db96d56Sopenharmony_ci   may either be an object with a :meth:`~io.IOBase.fileno` method (such as
10257db96d56Sopenharmony_ci   a file or socket object), or an integer file descriptor. The *mask*
10267db96d56Sopenharmony_ci   argument is an ORed combination of any of the three constants below.
10277db96d56Sopenharmony_ci   The callback is called as follows::
10287db96d56Sopenharmony_ci
10297db96d56Sopenharmony_ci      callback(file, mask)
10307db96d56Sopenharmony_ci
10317db96d56Sopenharmony_ci
10327db96d56Sopenharmony_ci.. method:: Widget.tk.deletefilehandler(file)
10337db96d56Sopenharmony_ci
10347db96d56Sopenharmony_ci   Unregisters a file handler.
10357db96d56Sopenharmony_ci
10367db96d56Sopenharmony_ci
10377db96d56Sopenharmony_ci.. data:: READABLE
10387db96d56Sopenharmony_ci          WRITABLE
10397db96d56Sopenharmony_ci          EXCEPTION
10407db96d56Sopenharmony_ci
10417db96d56Sopenharmony_ci   Constants used in the *mask* arguments.
1042