Home | History | Annotate | Download | only in library
      1 :mod:`Tkinter` --- Python interface to Tcl/Tk
      2 =============================================
      3 
      4 .. module:: Tkinter
      5    :synopsis: Interface to Tcl/Tk for graphical user interfaces
      6 .. moduleauthor:: Guido van Rossum <guido (a] Python.org>
      7 
      8 
      9 The :mod:`Tkinter` module ("Tk interface") is the standard Python interface to
     10 the Tk GUI toolkit.  Both Tk and :mod:`Tkinter` are available on most Unix
     11 platforms, as well as on Windows systems.  (Tk itself is not part of Python; it
     12 is maintained at ActiveState.)
     13 
     14 Running ``python -m Tkinter`` from the command line should open a window
     15 demonstrating a simple Tk interface, letting you know that :mod:`Tkinter` is
     16 properly installed on your system, and also showing what version of Tcl/Tk is
     17 installed, so you can read the Tcl/Tk documentation specific to that version.
     18 
     19 .. note::
     20 
     21    :mod:`Tkinter` has been renamed to :mod:`tkinter` in Python 3.  The
     22    :term:`2to3` tool will automatically adapt imports when converting your
     23    sources to Python 3.
     24 
     25 .. seealso::
     26 
     27    Tkinter documentation:
     28 
     29    `Python Tkinter Resources <https://wiki.python.org/moin/TkInter>`_
     30       The Python Tkinter Topic Guide provides a great deal of information on using Tk
     31       from Python and links to other sources of information on Tk.
     32 
     33    `TKDocs <http://www.tkdocs.com/>`_
     34       Extensive tutorial plus friendlier widget pages for some of the widgets.
     35 
     36    `Tkinter reference: a GUI for Python <https://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html>`_
     37       On-line reference material.
     38 
     39    `Tkinter docs from effbot <http://effbot.org/tkinterbook/>`_
     40       Online reference for tkinter supported by effbot.org.
     41 
     42    `Programming Python <http://learning-python.com/about-pp4e.html>`_
     43       Book by Mark Lutz, has excellent coverage of Tkinter.
     44 
     45    `Modern Tkinter for Busy Python Developers <https://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/>`_
     46       Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.
     47 
     48    `Python and Tkinter Programming <https://www.manning.com/books/python-and-tkinter-programming>`_
     49       Book by John Grayson (ISBN 1-884777-81-3).
     50 
     51    Tcl/Tk documentation:
     52 
     53    `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
     54       Most commands are available as :mod:`Tkinter` or :mod:`Tkinter.ttk` classes.
     55       Change '8.6' to match the version of your Tcl/Tk installation.
     56 
     57    `Tcl/Tk recent man pages <https://www.tcl.tk/doc/>`_
     58       Recent Tcl/Tk manuals on www.tcl.tk.
     59 
     60    `ActiveState Tcl Home Page <http://tcl.activestate.com/>`_
     61       The Tk/Tcl development is largely taking place at ActiveState.
     62 
     63    `Tcl and the Tk Toolkit <https://www.amazon.com/exec/obidos/ASIN/020163337X>`_
     64       Book by John Ousterhout, the inventor of Tcl.
     65 
     66    `Practical Programming in Tcl and Tk <http://www.beedub.com/book/>`_
     67       Brent Welch's encyclopedic book.
     68 
     69 
     70 Tkinter Modules
     71 ---------------
     72 
     73 Most of the time, the :mod:`Tkinter` module is all you really need, but a number
     74 of additional modules are available as well.  The Tk interface is located in a
     75 binary module named :mod:`_tkinter`. This module contains the low-level
     76 interface to Tk, and should never be used directly by application programmers.
     77 It is usually a shared library (or DLL), but might in some cases be statically
     78 linked with the Python interpreter.
     79 
     80 In addition to the Tk interface module, :mod:`Tkinter` includes a number of
     81 Python modules. The two most important modules are the :mod:`Tkinter` module
     82 itself, and a module called :mod:`Tkconstants`. The former automatically imports
     83 the latter, so to use Tkinter, all you need to do is to import one module::
     84 
     85    import Tkinter
     86 
     87 Or, more often::
     88 
     89    from Tkinter import *
     90 
     91 
     92 .. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
     93 
     94    The :class:`Tk` class is instantiated without arguments. This creates a toplevel
     95    widget of Tk which usually is the main window of an application. Each instance
     96    has its own associated Tcl interpreter.
     97 
     98    .. FIXME: The following keyword arguments are currently recognized:
     99 
    100    .. versionchanged:: 2.4
    101       The *useTk* parameter was added.
    102 
    103 
    104 .. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
    105 
    106    The :func:`Tcl` function is a factory function which creates an object much like
    107    that created by the :class:`Tk` class, except that it does not initialize the Tk
    108    subsystem.  This is most often useful when driving the Tcl interpreter in an
    109    environment where one doesn't want to create extraneous toplevel windows, or
    110    where one cannot (such as Unix/Linux systems without an X server).  An object
    111    created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
    112    subsystem initialized) by calling its :meth:`loadtk` method.
    113 
    114    .. versionadded:: 2.4
    115 
    116 Other modules that provide Tk support include:
    117 
    118 :mod:`ScrolledText`
    119    Text widget with a vertical scroll bar built in.
    120 
    121 :mod:`tkColorChooser`
    122    Dialog to let the user choose a color.
    123 
    124 :mod:`tkCommonDialog`
    125    Base class for the dialogs defined in the other modules listed here.
    126 
    127 :mod:`tkFileDialog`
    128    Common dialogs to allow the user to specify a file to open or save.
    129 
    130 :mod:`tkFont`
    131    Utilities to help work with fonts.
    132 
    133 :mod:`tkMessageBox`
    134    Access to standard Tk dialog boxes.
    135 
    136 :mod:`tkSimpleDialog`
    137    Basic dialogs and convenience functions.
    138 
    139 :mod:`Tkdnd`
    140    Drag-and-drop support for :mod:`Tkinter`. This is experimental and should become
    141    deprecated when it is replaced  with the Tk DND.
    142 
    143 :mod:`turtle`
    144    Turtle graphics in a Tk window.
    145 
    146 These have been renamed as well in Python 3; they were all made submodules of
    147 the new ``tkinter`` package.
    148 
    149 
    150 Tkinter Life Preserver
    151 ----------------------
    152 
    153 .. sectionauthor:: Matt Conway
    154 
    155 
    156 This section is not designed to be an exhaustive tutorial on either Tk or
    157 Tkinter.  Rather, it is intended as a stop gap, providing some introductory
    158 orientation on the system.
    159 
    160 Credits:
    161 
    162 * Tkinter was written by Steen Lumholt and Guido van Rossum.
    163 
    164 * Tk was written by John Ousterhout while at Berkeley.
    165 
    166 * This Life Preserver was written by Matt Conway at the University of Virginia.
    167 
    168 * The html rendering, and some liberal editing, was produced from a FrameMaker
    169   version by Ken Manheimer.
    170 
    171 * Fredrik Lundh elaborated and revised the class interface descriptions, to get
    172   them current with Tk 4.2.
    173 
    174 * Mike Clarkson converted the documentation to LaTeX, and compiled the  User
    175   Interface chapter of the reference manual.
    176 
    177 
    178 How To Use This Section
    179 ^^^^^^^^^^^^^^^^^^^^^^^
    180 
    181 This section is designed in two parts: the first half (roughly) covers
    182 background material, while the second half can be taken to the keyboard as a
    183 handy reference.
    184 
    185 When trying to answer questions of the form "how do I do blah", it is often best
    186 to find out how to do "blah" in straight Tk, and then convert this back into the
    187 corresponding :mod:`Tkinter` call. Python programmers can often guess at the
    188 correct Python command by looking at the Tk documentation. This means that in
    189 order to use Tkinter, you will have to know a little bit about Tk. This document
    190 can't fulfill that role, so the best we can do is point you to the best
    191 documentation that exists. Here are some hints:
    192 
    193 * The authors strongly suggest getting a copy of the Tk man pages. Specifically,
    194   the man pages in the ``mann`` directory are most useful. The ``man3`` man pages
    195   describe the C interface to the Tk library and thus are not especially helpful
    196   for script writers.
    197 
    198 * Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
    199   Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
    200   the novice.  The book is not exhaustive, and for many details it defers to the
    201   man pages.
    202 
    203 * :file:`Tkinter.py` is a last resort for most, but can be a good place to go
    204   when nothing else makes sense.
    205 
    206 
    207 A Simple Hello World Program
    208 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    209 
    210 ::
    211 
    212    from Tkinter import *
    213 
    214    class Application(Frame):
    215        def say_hi(self):
    216            print "hi there, everyone!"
    217 
    218        def createWidgets(self):
    219            self.QUIT = Button(self)
    220            self.QUIT["text"] = "QUIT"
    221            self.QUIT["fg"]   = "red"
    222            self.QUIT["command"] =  self.quit
    223 
    224            self.QUIT.pack({"side": "left"})
    225 
    226            self.hi_there = Button(self)
    227            self.hi_there["text"] = "Hello",
    228            self.hi_there["command"] = self.say_hi
    229 
    230            self.hi_there.pack({"side": "left"})
    231 
    232        def __init__(self, master=None):
    233            Frame.__init__(self, master)
    234            self.pack()
    235            self.createWidgets()
    236 
    237    root = Tk()
    238    app = Application(master=root)
    239    app.mainloop()
    240    root.destroy()
    241 
    242 
    243 A (Very) Quick Look at Tcl/Tk
    244 -----------------------------
    245 
    246 The class hierarchy looks complicated, but in actual practice, application
    247 programmers almost always refer to the classes at the very bottom of the
    248 hierarchy.
    249 
    250 Notes:
    251 
    252 * These classes are provided for the purposes of organizing certain functions
    253   under one namespace. They aren't meant to be instantiated independently.
    254 
    255 * The :class:`Tk` class is meant to be instantiated only once in an application.
    256   Application programmers need not instantiate one explicitly, the system creates
    257   one whenever any of the other classes are instantiated.
    258 
    259 * The :class:`Widget` class is not meant to be instantiated, it is meant only
    260   for subclassing to make "real" widgets (in C++, this is called an 'abstract
    261   class').
    262 
    263 To make use of this reference material, there will be times when you will need
    264 to know how to read short passages of Tk and how to identify the various parts
    265 of a Tk command.   (See section :ref:`tkinter-basic-mapping` for the
    266 :mod:`Tkinter` equivalents of what's below.)
    267 
    268 Tk scripts are Tcl programs.  Like all Tcl programs, Tk scripts are just lists
    269 of tokens separated by spaces.  A Tk widget is just its *class*, the *options*
    270 that help configure it, and the *actions* that make it do useful things.
    271 
    272 To make a widget in Tk, the command is always of the form::
    273 
    274    classCommand newPathname options
    275 
    276 *classCommand*
    277    denotes which kind of widget to make (a button, a label, a menu...)
    278 
    279 *newPathname*
    280    is the new name for this widget.  All names in Tk must be unique.  To help
    281    enforce this, widgets in Tk are named with *pathnames*, just like files in a
    282    file system.  The top level widget, the *root*, is called ``.`` (period) and
    283    children are delimited by more periods.  For example,
    284    ``.myApp.controlPanel.okButton`` might be the name of a widget.
    285 
    286 *options*
    287    configure the widget's appearance and in some cases, its behavior.  The options
    288    come in the form of a list of flags and values. Flags are preceded by a '-',
    289    like Unix shell command flags, and values are put in quotes if they are more
    290    than one word.
    291 
    292 For example::
    293 
    294    button   .fred   -fg red -text "hi there"
    295       ^       ^     \_____________________/
    296       |       |                |
    297     class    new            options
    298    command  widget  (-opt val -opt val ...)
    299 
    300 Once created, the pathname to the widget becomes a new command.  This new
    301 *widget command* is the programmer's handle for getting the new widget to
    302 perform some *action*.  In C, you'd express this as someAction(fred,
    303 someOptions), in C++, you would express this as fred.someAction(someOptions),
    304 and in Tk, you say::
    305 
    306    .fred someAction someOptions
    307 
    308 Note that the object name, ``.fred``, starts with a dot.
    309 
    310 As you'd expect, the legal values for *someAction* will depend on the widget's
    311 class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
    312 does not work if fred is a label (disabling of labels is not supported in Tk).
    313 
    314 The legal values of *someOptions* is action dependent.  Some actions, like
    315 ``disable``, require no arguments, others, like a text-entry box's ``delete``
    316 command, would need arguments to specify what range of text to delete.
    317 
    318 
    319 .. _tkinter-basic-mapping:
    320 
    321 Mapping Basic Tk into Tkinter
    322 -----------------------------
    323 
    324 Class commands in Tk correspond to class constructors in Tkinter. ::
    325 
    326    button .fred                =====>  fred = Button()
    327 
    328 The master of an object is implicit in the new name given to it at creation
    329 time.  In Tkinter, masters are specified explicitly. ::
    330 
    331    button .panel.fred          =====>  fred = Button(panel)
    332 
    333 The configuration options in Tk are given in lists of hyphened tags followed by
    334 values.  In Tkinter, options are specified as keyword-arguments in the instance
    335 constructor, and keyword-args for configure calls or as instance indices, in
    336 dictionary style, for established instances.  See section
    337 :ref:`tkinter-setting-options` on setting options. ::
    338 
    339    button .fred -fg red        =====>  fred = Button(panel, fg = "red")
    340    .fred configure -fg red     =====>  fred["fg"] = red
    341                                OR ==>  fred.config(fg = "red")
    342 
    343 In Tk, to perform an action on a widget, use the widget name as a command, and
    344 follow it with an action name, possibly with arguments (options).  In Tkinter,
    345 you call methods on the class instance to invoke actions on the widget.  The
    346 actions (methods) that a given widget can perform are listed in the Tkinter.py
    347 module. ::
    348 
    349    .fred invoke                =====>  fred.invoke()
    350 
    351 To give a widget to the packer (geometry manager), you call pack with optional
    352 arguments.  In Tkinter, the Pack class holds all this functionality, and the
    353 various forms of the pack command are implemented as methods.  All widgets in
    354 :mod:`Tkinter` are subclassed from the Packer, and so inherit all the packing
    355 methods. See the :mod:`Tix` module documentation for additional information on
    356 the Form geometry manager. ::
    357 
    358    pack .fred -side left       =====>  fred.pack(side = "left")
    359 
    360 
    361 How Tk and Tkinter are Related
    362 ------------------------------
    363 
    364 From the top down:
    365 
    366 Your App Here (Python)
    367    A Python application makes a :mod:`Tkinter` call.
    368 
    369 Tkinter (Python Module)
    370    This call (say, for example, creating a button widget), is implemented in the
    371    *Tkinter* module, which is written in Python.  This Python function will parse
    372    the commands and the arguments and convert them into a form that makes them look
    373    as if they had come from a Tk script instead of a Python script.
    374 
    375 tkinter (C)
    376    These commands and their arguments will be passed to a C function in the
    377    *tkinter* - note the lowercase - extension module.
    378 
    379 Tk Widgets (C and Tcl)
    380    This C function is able to make calls into other C modules, including the C
    381    functions that make up the Tk library.  Tk is implemented in C and some Tcl.
    382    The Tcl part of the Tk widgets is used to bind certain default behaviors to
    383    widgets, and is executed once at the point where the Python :mod:`Tkinter`
    384    module is imported. (The user never sees this stage).
    385 
    386 Tk (C)
    387    The Tk part of the Tk Widgets implement the final mapping to ...
    388 
    389 Xlib (C)
    390    the Xlib library to draw graphics on the screen.
    391 
    392 
    393 Handy Reference
    394 ---------------
    395 
    396 
    397 .. _tkinter-setting-options:
    398 
    399 Setting Options
    400 ^^^^^^^^^^^^^^^
    401 
    402 Options control things like the color and border width of a widget. Options can
    403 be set in three ways:
    404 
    405 At object creation time, using keyword arguments
    406    ::
    407 
    408       fred = Button(self, fg = "red", bg = "blue")
    409 
    410 After object creation, treating the option name like a dictionary index
    411    ::
    412 
    413       fred["fg"] = "red"
    414       fred["bg"] = "blue"
    415 
    416 Use the config() method to update multiple attrs subsequent to object creation
    417    ::
    418 
    419       fred.config(fg = "red", bg = "blue")
    420 
    421 For a complete explanation of a given option and its behavior, see the Tk man
    422 pages for the widget in question.
    423 
    424 Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
    425 for each widget.  The former is a list of options that are common to many
    426 widgets, the latter are the options that are idiosyncratic to that particular
    427 widget.  The Standard Options are documented on the :manpage:`options(3)` man
    428 page.
    429 
    430 No distinction between standard and widget-specific options is made in this
    431 document.  Some options don't apply to some kinds of widgets. Whether a given
    432 widget responds to a particular option depends on the class of the widget;
    433 buttons have a ``command`` option, labels do not.
    434 
    435 The options supported by a given widget are listed in that widget's man page, or
    436 can be queried at runtime by calling the :meth:`config` method without
    437 arguments, or by calling the :meth:`keys` method on that widget.  The return
    438 value of these calls is a dictionary whose key is the name of the option as a
    439 string (for example, ``'relief'``) and whose values are 5-tuples.
    440 
    441 Some options, like ``bg`` are synonyms for common options with long names
    442 (``bg`` is shorthand for "background"). Passing the ``config()`` method the name
    443 of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
    444 back will contain the name of the synonym and the "real" option (such as
    445 ``('bg', 'background')``).
    446 
    447 +-------+---------------------------------+--------------+
    448 | Index | Meaning                         | Example      |
    449 +=======+=================================+==============+
    450 | 0     | option name                     | ``'relief'`` |
    451 +-------+---------------------------------+--------------+
    452 | 1     | option name for database lookup | ``'relief'`` |
    453 +-------+---------------------------------+--------------+
    454 | 2     | option class for database       | ``'Relief'`` |
    455 |       | lookup                          |              |
    456 +-------+---------------------------------+--------------+
    457 | 3     | default value                   | ``'raised'`` |
    458 +-------+---------------------------------+--------------+
    459 | 4     | current value                   | ``'groove'`` |
    460 +-------+---------------------------------+--------------+
    461 
    462 Example::
    463 
    464    >>> print fred.config()
    465    {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}
    466 
    467 Of course, the dictionary printed will include all the options available and
    468 their values.  This is meant only as an example.
    469 
    470 
    471 The Packer
    472 ^^^^^^^^^^
    473 
    474 .. index:: single: packing (widgets)
    475 
    476 The packer is one of Tk's geometry-management mechanisms.    Geometry managers
    477 are used to specify the relative positioning of the positioning of widgets
    478 within their container - their mutual *master*.  In contrast to the more
    479 cumbersome *placer* (which is used less commonly, and we do not cover here), the
    480 packer takes qualitative relationship specification - *above*, *to the left of*,
    481 *filling*, etc - and works everything out to determine the exact placement
    482 coordinates for you.
    483 
    484 The size of any *master* widget is determined by the size of the "slave widgets"
    485 inside.  The packer is used to control where slave widgets appear inside the
    486 master into which they are packed.  You can pack widgets into frames, and frames
    487 into other frames, in order to achieve the kind of layout you desire.
    488 Additionally, the arrangement is dynamically adjusted to accommodate incremental
    489 changes to the configuration, once it is packed.
    490 
    491 Note that widgets do not appear until they have had their geometry specified
    492 with a geometry manager.  It's a common early mistake to leave out the geometry
    493 specification, and then be surprised when the widget is created but nothing
    494 appears.  A widget will appear only after it has had, for example, the packer's
    495 :meth:`pack` method applied to it.
    496 
    497 The pack() method can be called with keyword-option/value pairs that control
    498 where the widget is to appear within its container, and how it is to behave when
    499 the main application window is resized.  Here are some examples::
    500 
    501    fred.pack()                     # defaults to side = "top"
    502    fred.pack(side = "left")
    503    fred.pack(expand = 1)
    504 
    505 
    506 Packer Options
    507 ^^^^^^^^^^^^^^
    508 
    509 For more extensive information on the packer and the options that it can take,
    510 see the man pages and page 183 of John Ousterhout's book.
    511 
    512 anchor
    513    Anchor type.  Denotes where the packer is to place each slave in its parcel.
    514 
    515 expand
    516    Boolean, ``0`` or ``1``.
    517 
    518 fill
    519    Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
    520 
    521 ipadx and ipady
    522    A distance - designating internal padding on each side of the slave widget.
    523 
    524 padx and pady
    525    A distance - designating external padding on each side of the slave widget.
    526 
    527 side
    528    Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
    529 
    530 
    531 Coupling Widget Variables
    532 ^^^^^^^^^^^^^^^^^^^^^^^^^
    533 
    534 The current-value setting of some widgets (like text entry widgets) can be
    535 connected directly to application variables by using special options.  These
    536 options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
    537 ``value``.  This connection works both ways: if the variable changes for any
    538 reason, the widget it's connected to will be updated to reflect the new value.
    539 
    540 Unfortunately, in the current implementation of :mod:`Tkinter` it is not
    541 possible to hand over an arbitrary Python variable to a widget through a
    542 ``variable`` or ``textvariable`` option.  The only kinds of variables for which
    543 this works are variables that are subclassed from a class called Variable,
    544 defined in the :mod:`Tkinter` module.
    545 
    546 There are many useful subclasses of Variable already defined:
    547 :class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
    548 :class:`BooleanVar`.  To read the current value of such a variable, call the
    549 :meth:`get` method on it, and to change its value you call the :meth:`!set`
    550 method.  If you follow this protocol, the widget will always track the value of
    551 the variable, with no further intervention on your part.
    552 
    553 For example::
    554 
    555    class App(Frame):
    556        def __init__(self, master=None):
    557            Frame.__init__(self, master)
    558            self.pack()
    559 
    560            self.entrythingy = Entry()
    561            self.entrythingy.pack()
    562 
    563            # here is the application variable
    564            self.contents = StringVar()
    565            # set it to some value
    566            self.contents.set("this is a variable")
    567            # tell the entry widget to watch this variable
    568            self.entrythingy["textvariable"] = self.contents
    569 
    570            # and here we get a callback when the user hits return.
    571            # we will have the program print out the value of the
    572            # application variable when the user hits return
    573            self.entrythingy.bind('<Key-Return>',
    574                                  self.print_contents)
    575 
    576        def print_contents(self, event):
    577            print "hi. contents of entry is now ---->", \
    578                  self.contents.get()
    579 
    580 
    581 The Window Manager
    582 ^^^^^^^^^^^^^^^^^^
    583 
    584 .. index:: single: window manager (widgets)
    585 
    586 In Tk, there is a utility command, ``wm``, for interacting with the window
    587 manager.  Options to the ``wm`` command allow you to control things like titles,
    588 placement, icon bitmaps, and the like.  In :mod:`Tkinter`, these commands have
    589 been implemented as methods on the :class:`Wm` class.  Toplevel widgets are
    590 subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
    591 directly.
    592 
    593 To get at the toplevel window that contains a given widget, you can often just
    594 refer to the widget's master.  Of course if the widget has been packed inside of
    595 a frame, the master won't represent a toplevel window.  To get at the toplevel
    596 window that contains an arbitrary widget, you can call the :meth:`_root` method.
    597 This method begins with an underscore to denote the fact that this function is
    598 part of the implementation, and not an interface to Tk functionality.
    599 
    600 Here are some examples of typical usage::
    601 
    602    from Tkinter import *
    603    class App(Frame):
    604        def __init__(self, master=None):
    605            Frame.__init__(self, master)
    606            self.pack()
    607 
    608 
    609    # create the application
    610    myapp = App()
    611 
    612    #
    613    # here are method calls to the window manager class
    614    #
    615    myapp.master.title("My Do-Nothing Application")
    616    myapp.master.maxsize(1000, 400)
    617 
    618    # start the program
    619    myapp.mainloop()
    620 
    621 
    622 Tk Option Data Types
    623 ^^^^^^^^^^^^^^^^^^^^
    624 
    625 .. index:: single: Tk Option Data Types
    626 
    627 anchor
    628    Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
    629    ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
    630 
    631 bitmap
    632    There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
    633    ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
    634    ``'warning'``.  To specify an X bitmap filename, give the full path to the file,
    635    preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
    636 
    637 boolean
    638    You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.
    639 
    640 callback
    641    This is any Python function that takes no arguments.  For example::
    642 
    643       def print_it():
    644               print "hi there"
    645       fred["command"] = print_it
    646 
    647 color
    648    Colors can be given as the names of X colors in the rgb.txt file, or as strings
    649    representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
    650    ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
    651    represent any legal hex digit.  See page 160 of Ousterhout's book for details.
    652 
    653 cursor
    654    The standard X cursor names from :file:`cursorfont.h` can be used, without the
    655    ``XC_`` prefix.  For example to get a hand cursor (:const:`XC_hand2`), use the
    656    string ``"hand2"``.  You can also specify a bitmap and mask file of your own.
    657    See page 179 of Ousterhout's book.
    658 
    659 distance
    660    Screen distances can be specified in either pixels or absolute distances.
    661    Pixels are given as numbers and absolute distances as strings, with the trailing
    662    character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
    663    millimetres, ``p`` for printer's points.  For example, 3.5 inches is expressed
    664    as ``"3.5i"``.
    665 
    666 font
    667    Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
    668    positive numbers are measured in points; sizes with negative numbers are
    669    measured in pixels.
    670 
    671 geometry
    672    This is a string of the form ``widthxheight``, where width and height are
    673    measured in pixels for most widgets (in characters for widgets displaying text).
    674    For example: ``fred["geometry"] = "200x100"``.
    675 
    676 justify
    677    Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
    678    ``"fill"``.
    679 
    680 region
    681    This is a string with four space-delimited elements, each of which is a legal
    682    distance (see above).  For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
    683    ``"3c 2c 4c 10.43c"``  are all legal regions.
    684 
    685 relief
    686    Determines what the border style of a widget will be.  Legal values are:
    687    ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
    688 
    689 scrollcommand
    690    This is almost always the :meth:`!set` method of some scrollbar widget, but can
    691    be any widget method that takes a single argument.   Refer to the file
    692    :file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
    693    distribution for an example.
    694 
    695 wrap:
    696    Must be one of: ``"none"``, ``"char"``, or ``"word"``.
    697 
    698 
    699 Bindings and Events
    700 ^^^^^^^^^^^^^^^^^^^
    701 
    702 .. index::
    703    single: bind (widgets)
    704    single: events (widgets)
    705 
    706 The bind method from the widget command allows you to watch for certain events
    707 and to have a callback function trigger when that event type occurs.  The form
    708 of the bind method is::
    709 
    710    def bind(self, sequence, func, add=''):
    711 
    712 where:
    713 
    714 sequence
    715    is a string that denotes the target kind of event.  (See the bind man page and
    716    page 201 of John Ousterhout's book for details).
    717 
    718 func
    719    is a Python function, taking one argument, to be invoked when the event occurs.
    720    An Event instance will be passed as the argument. (Functions deployed this way
    721    are commonly known as *callbacks*.)
    722 
    723 add
    724    is optional, either ``''`` or ``'+'``.  Passing an empty string denotes that
    725    this binding is to replace any other bindings that this event is associated
    726    with.  Passing a ``'+'`` means that this function is to be added to the list
    727    of functions bound to this event type.
    728 
    729 For example::
    730 
    731    def turnRed(self, event):
    732        event.widget["activeforeground"] = "red"
    733 
    734    self.button.bind("<Enter>", self.turnRed)
    735 
    736 Notice how the widget field of the event is being accessed in the
    737 :meth:`turnRed` callback.  This field contains the widget that caught the X
    738 event.  The following table lists the other event fields you can access, and how
    739 they are denoted in Tk, which can be useful when referring to the Tk man pages.
    740 ::
    741 
    742    Tk      Tkinter Event Field             Tk      Tkinter Event Field
    743    --      -------------------             --      -------------------
    744    %f      focus                           %A      char
    745    %h      height                          %E      send_event
    746    %k      keycode                         %K      keysym
    747    %s      state                           %N      keysym_num
    748    %t      time                            %T      type
    749    %w      width                           %W      widget
    750    %x      x                               %X      x_root
    751    %y      y                               %Y      y_root
    752 
    753 
    754 The index Parameter
    755 ^^^^^^^^^^^^^^^^^^^
    756 
    757 A number of widgets require"index" parameters to be passed.  These are used to
    758 point at a specific place in a Text widget, or to particular characters in an
    759 Entry widget, or to particular menu items in a Menu widget.
    760 
    761 Entry widget indexes (index, view index, etc.)
    762    Entry widgets have options that refer to character positions in the text being
    763    displayed.  You can use these :mod:`Tkinter` functions to access these special
    764    points in text widgets:
    765 
    766    AtEnd()
    767       refers to the last position in the text
    768 
    769    AtInsert()
    770       refers to the point where the text cursor is
    771 
    772    AtSelFirst()
    773       indicates the beginning point of the selected text
    774 
    775    AtSelLast()
    776       denotes the last point of the selected text and finally
    777 
    778    At(x[, y])
    779       refers to the character at pixel location *x*, *y* (with *y* not used in the
    780       case of a text entry widget, which contains a single line of text).
    781 
    782 Text widget indexes
    783    The index notation for Text widgets is very rich and is best described in the Tk
    784    man pages.
    785 
    786 Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
    787    Some options and methods for menus manipulate specific menu entries. Anytime a
    788    menu index is needed for an option or a parameter, you may pass in:
    789 
    790    * an integer which refers to the numeric position of the entry in the widget,
    791      counted from the top, starting with 0;
    792 
    793    * the string ``'active'``, which refers to the menu position that is currently
    794      under the cursor;
    795 
    796    * the string ``"last"`` which refers to the last menu item;
    797 
    798    * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
    799      as a y pixel coordinate in the menu's coordinate system;
    800 
    801    * the string ``"none"``, which indicates no menu entry at all, most often used
    802      with menu.activate() to deactivate all entries, and finally,
    803 
    804    * a text string that is pattern matched against the label of the menu entry, as
    805      scanned from the top of the menu to the bottom.  Note that this index type is
    806      considered after all the others, which means that matches for menu items
    807      labelled ``last``, ``active``, or ``none`` may be interpreted as the above
    808      literals, instead.
    809 
    810 
    811 Images
    812 ^^^^^^
    813 
    814 Images of different formats can be created through the corresponding subclass
    815 of :class:`Tkinter.Image`:
    816 
    817 * :class:`BitmapImage` for images in XBM format.
    818 
    819 * :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter
    820   is supported starting with Tk 8.6.
    821 
    822 Either type of image is created through either the ``file`` or the ``data``
    823 option (other options are available as well).
    824 
    825 The image object can then be used wherever an ``image`` option is supported by
    826 some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
    827 reference to the image. When the last Python reference to the image object is
    828 deleted, the image data is deleted as well, and Tk will display an empty box
    829 wherever the image was used.
    830 
    831 .. seealso::
    832 
    833     The `Pillow <http://python-pillow.org/>`_ package adds support for
    834     formats such as BMP, JPEG, TIFF, and WebP, among others.
    835 
    836 .. _tkinter-file-handlers:
    837 
    838 File Handlers
    839 -------------
    840 
    841 Tk allows you to register and unregister a callback function which will be
    842 called from the Tk mainloop when I/O is possible on a file descriptor.
    843 Only one handler may be registered per file descriptor. Example code::
    844 
    845    import Tkinter
    846    widget = Tkinter.Tk()
    847    mask = Tkinter.READABLE | Tkinter.WRITABLE
    848    widget.tk.createfilehandler(file, mask, callback)
    849    ...
    850    widget.tk.deletefilehandler(file)
    851 
    852 This feature is not available on Windows.
    853 
    854 Since you don't know how many bytes are available for reading, you may not
    855 want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
    856 :meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods,
    857 since these will insist on reading a predefined number of bytes.
    858 For sockets, the :meth:`~socket.socket.recv` or
    859 :meth:`~socket.socket.recvfrom` methods will work fine; for other files,
    860 use raw reads or ``os.read(file.fileno(), maxbytecount)``.
    861 
    862 
    863 .. method:: Widget.tk.createfilehandler(file, mask, func)
    864 
    865    Registers the file handler callback function *func*. The *file* argument
    866    may either be an object with a :meth:`~io.IOBase.fileno` method (such as
    867    a file or socket object), or an integer file descriptor. The *mask*
    868    argument is an ORed combination of any of the three constants below.
    869    The callback is called as follows::
    870 
    871       callback(file, mask)
    872 
    873 
    874 .. method:: Widget.tk.deletefilehandler(file)
    875 
    876    Unregisters a file handler.
    877 
    878 
    879 .. data:: READABLE
    880           WRITABLE
    881           EXCEPTION
    882 
    883    Constants used in the *mask* arguments.
    884 
    885