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