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