PageRenderTime 66ms CodeModel.GetById 11ms app.highlight 45ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/library/tkinter.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 810 lines | 577 code | 233 blank | 0 comment | 0 complexity | cd73abc3503766279796d7fb03cd5add MD5 | raw file
  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.0.  The
 17   :term:`2to3` tool will automatically adapt imports when converting your
 18   sources to 3.0.
 19
 20.. seealso::
 21
 22   `Python Tkinter Resources <http://www.python.org/topics/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   `An Introduction to Tkinter <http://www.pythonware.com/library/an-introduction-to-tkinter.htm>`_
 27      Fredrik Lundh's on-line reference material.
 28
 29   `Tkinter reference: a GUI for Python <http://infohost.nmt.edu/tcc/help/pubs/lang.html>`_
 30      On-line reference material.
 31
 32   `Tkinter for JPython <http://jtkinter.sourceforge.net>`_
 33      The Jython interface to Tkinter.
 34
 35   `Python and Tkinter Programming <http://www.amazon.com/exec/obidos/ASIN/1884777813>`_
 36      The book by John Grayson (ISBN 1-884777-81-3).
 37
 38
 39Tkinter Modules
 40---------------
 41
 42Most of the time, the :mod:`Tkinter` module is all you really need, but a number
 43of additional modules are available as well.  The Tk interface is located in a
 44binary module named :mod:`_tkinter`. This module contains the low-level
 45interface to Tk, and should never be used directly by application programmers.
 46It is usually a shared library (or DLL), but might in some cases be statically
 47linked with the Python interpreter.
 48
 49In addition to the Tk interface module, :mod:`Tkinter` includes a number of
 50Python modules. The two most important modules are the :mod:`Tkinter` module
 51itself, and a module called :mod:`Tkconstants`. The former automatically imports
 52the latter, so to use Tkinter, all you need to do is to import one module::
 53
 54   import Tkinter
 55
 56Or, more often::
 57
 58   from Tkinter import *
 59
 60
 61.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
 62
 63   The :class:`Tk` class is instantiated without arguments. This creates a toplevel
 64   widget of Tk which usually is the main window of an application. Each instance
 65   has its own associated Tcl interpreter.
 66
 67   .. FIXME: The following keyword arguments are currently recognized:
 68
 69   .. versionchanged:: 2.4
 70      The *useTk* parameter was added.
 71
 72
 73.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
 74
 75   The :func:`Tcl` function is a factory function which creates an object much like
 76   that created by the :class:`Tk` class, except that it does not initialize the Tk
 77   subsystem.  This is most often useful when driving the Tcl interpreter in an
 78   environment where one doesn't want to create extraneous toplevel windows, or
 79   where one cannot (such as Unix/Linux systems without an X server).  An object
 80   created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
 81   subsystem initialized) by calling its :meth:`loadtk` method.
 82
 83   .. versionadded:: 2.4
 84
 85Other modules that provide Tk support include:
 86
 87:mod:`ScrolledText`
 88   Text widget with a vertical scroll bar built in.
 89
 90:mod:`tkColorChooser`
 91   Dialog to let the user choose a color.
 92
 93:mod:`tkCommonDialog`
 94   Base class for the dialogs defined in the other modules listed here.
 95
 96:mod:`tkFileDialog`
 97   Common dialogs to allow the user to specify a file to open or save.
 98
 99:mod:`tkFont`
100   Utilities to help work with fonts.
101
102:mod:`tkMessageBox`
103   Access to standard Tk dialog boxes.
104
105:mod:`tkSimpleDialog`
106   Basic dialogs and convenience functions.
107
108:mod:`Tkdnd`
109   Drag-and-drop support for :mod:`Tkinter`. This is experimental and should become
110   deprecated when it is replaced  with the Tk DND.
111
112:mod:`turtle`
113   Turtle graphics in a Tk window.
114
115These have been renamed as well in Python 3.0; they were all made submodules of
116the new ``tkinter`` package.
117
118
119Tkinter Life Preserver
120----------------------
121
122.. sectionauthor:: Matt Conway
123
124
125This section is not designed to be an exhaustive tutorial on either Tk or
126Tkinter.  Rather, it is intended as a stop gap, providing some introductory
127orientation on the system.
128
129Credits:
130
131* Tkinter was written by Steen Lumholt and Guido van Rossum.
132
133* Tk was written by John Ousterhout while at Berkeley.
134
135* This Life Preserver was written by Matt Conway at the University of Virginia.
136
137* The html rendering, and some liberal editing, was produced from a FrameMaker
138  version by Ken Manheimer.
139
140* Fredrik Lundh elaborated and revised the class interface descriptions, to get
141  them current with Tk 4.2.
142
143* Mike Clarkson converted the documentation to LaTeX, and compiled the  User
144  Interface chapter of the reference manual.
145
146
147How To Use This Section
148^^^^^^^^^^^^^^^^^^^^^^^
149
150This section is designed in two parts: the first half (roughly) covers
151background material, while the second half can be taken to the keyboard as a
152handy reference.
153
154When trying to answer questions of the form "how do I do blah", it is often best
155to find out how to do"blah" in straight Tk, and then convert this back into the
156corresponding :mod:`Tkinter` call. Python programmers can often guess at the
157correct Python command by looking at the Tk documentation. This means that in
158order to use Tkinter, you will have to know a little bit about Tk. This document
159can't fulfill that role, so the best we can do is point you to the best
160documentation that exists. Here are some hints:
161
162* The authors strongly suggest getting a copy of the Tk man pages. Specifically,
163  the man pages in the ``mann`` directory are most useful. The ``man3`` man pages
164  describe the C interface to the Tk library and thus are not especially helpful
165  for script writers.
166
167* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
168  Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
169  the novice.  The book is not exhaustive, and for many details it defers to the
170  man pages.
171
172* :file:`Tkinter.py` is a last resort for most, but can be a good place to go
173  when nothing else makes sense.
174
175
176.. seealso::
177
178   `ActiveState Tcl Home Page <http://tcl.activestate.com/>`_
179      The Tk/Tcl development is largely taking place at ActiveState.
180
181   `Tcl and the Tk Toolkit <http://www.amazon.com/exec/obidos/ASIN/020163337X>`_
182      The book by John Ousterhout, the inventor of Tcl .
183
184   `Practical Programming in Tcl and Tk <http://www.amazon.com/exec/obidos/ASIN/0130220280>`_
185      Brent Welch's encyclopedic book.
186
187
188A Simple Hello World Program
189^^^^^^^^^^^^^^^^^^^^^^^^^^^^
190
191::
192
193   from Tkinter import *
194
195   class Application(Frame):
196       def say_hi(self):
197           print "hi there, everyone!"
198
199       def createWidgets(self):
200           self.QUIT = Button(self)
201           self.QUIT["text"] = "QUIT"
202           self.QUIT["fg"]   = "red"
203           self.QUIT["command"] =  self.quit
204
205           self.QUIT.pack({"side": "left"})
206
207           self.hi_there = Button(self)
208           self.hi_there["text"] = "Hello",
209           self.hi_there["command"] = self.say_hi
210
211           self.hi_there.pack({"side": "left"})
212
213       def __init__(self, master=None):
214           Frame.__init__(self, master)
215           self.pack()
216           self.createWidgets()
217
218   root = Tk()
219   app = Application(master=root)
220   app.mainloop()
221   root.destroy()
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 the Tkinter.py
328module. ::
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:`Tix` module documentation for additional information on
337the 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 Module)
351   This call (say, for example, creating a button widget), is implemented in the
352   *Tkinter* module, which is written in Python.  This Python function will parse
353   the commands and the arguments and convert them into a form that makes them look
354   as if they had come from a Tk script instead of a Python script.
355
356tkinter (C)
357   These commands and their arguments will be passed to a C function in the
358   *tkinter* - note the lowercase - extension module.
359
360Tk Widgets (C and Tcl)
361   This C function is able to make calls into other C modules, including the C
362   functions that make up the Tk library.  Tk is implemented in C and some Tcl.
363   The Tcl part of the Tk widgets is used to bind certain default behaviors to
364   widgets, and is executed once at the point where the Python :mod:`Tkinter`
365   module is imported. (The user never sees this stage).
366
367Tk (C)
368   The Tk part of the Tk Widgets implement the final mapping to ...
369
370Xlib (C)
371   the Xlib library to draw graphics on the screen.
372
373
374Handy Reference
375---------------
376
377
378.. _tkinter-setting-options:
379
380Setting Options
381^^^^^^^^^^^^^^^
382
383Options control things like the color and border width of a widget. Options can
384be set in three ways:
385
386At object creation time, using keyword arguments
387   ::
388
389      fred = Button(self, fg = "red", bg = "blue")
390
391After object creation, treating the option name like a dictionary index
392   ::
393
394      fred["fg"] = "red"
395      fred["bg"] = "blue"
396
397Use the config() method to update multiple attrs subsequent to object creation
398   ::
399
400      fred.config(fg = "red", bg = "blue")
401
402For a complete explanation of a given option and its behavior, see the Tk man
403pages for the widget in question.
404
405Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
406for each widget.  The former is a list of options that are common to many
407widgets, the latter are the options that are idiosyncratic to that particular
408widget.  The Standard Options are documented on the :manpage:`options(3)` man
409page.
410
411No distinction between standard and widget-specific options is made in this
412document.  Some options don't apply to some kinds of widgets. Whether a given
413widget responds to a particular option depends on the class of the widget;
414buttons have a ``command`` option, labels do not.
415
416The options supported by a given widget are listed in that widget's man page, or
417can be queried at runtime by calling the :meth:`config` method without
418arguments, or by calling the :meth:`keys` method on that widget.  The return
419value of these calls is a dictionary whose key is the name of the option as a
420string (for example, ``'relief'``) and whose values are 5-tuples.
421
422Some options, like ``bg`` are synonyms for common options with long names
423(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
424of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
425back will contain the name of the synonym and the "real" option (such as
426``('bg', 'background')``).
427
428+-------+---------------------------------+--------------+
429| Index | Meaning                         | Example      |
430+=======+=================================+==============+
431| 0     | option name                     | ``'relief'`` |
432+-------+---------------------------------+--------------+
433| 1     | option name for database lookup | ``'relief'`` |
434+-------+---------------------------------+--------------+
435| 2     | option class for database       | ``'Relief'`` |
436|       | lookup                          |              |
437+-------+---------------------------------+--------------+
438| 3     | default value                   | ``'raised'`` |
439+-------+---------------------------------+--------------+
440| 4     | current value                   | ``'groove'`` |
441+-------+---------------------------------+--------------+
442
443Example::
444
445   >>> print fred.config()
446   {'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
447
448Of course, the dictionary printed will include all the options available and
449their values.  This is meant only as an example.
450
451
452The Packer
453^^^^^^^^^^
454
455.. index:: single: packing (widgets)
456
457The packer is one of Tk's geometry-management mechanisms.    Geometry managers
458are used to specify the relative positioning of the positioning of widgets
459within their container - their mutual *master*.  In contrast to the more
460cumbersome *placer* (which is used less commonly, and we do not cover here), the
461packer takes qualitative relationship specification - *above*, *to the left of*,
462*filling*, etc - and works everything out to determine the exact placement
463coordinates for you.
464
465The size of any *master* widget is determined by the size of the "slave widgets"
466inside.  The packer is used to control where slave widgets appear inside the
467master into which they are packed.  You can pack widgets into frames, and frames
468into other frames, in order to achieve the kind of layout you desire.
469Additionally, the arrangement is dynamically adjusted to accommodate incremental
470changes to the configuration, once it is packed.
471
472Note that widgets do not appear until they have had their geometry specified
473with a geometry manager.  It's a common early mistake to leave out the geometry
474specification, and then be surprised when the widget is created but nothing
475appears.  A widget will appear only after it has had, for example, the packer's
476:meth:`pack` method applied to it.
477
478The pack() method can be called with keyword-option/value pairs that control
479where the widget is to appear within its container, and how it is to behave when
480the main application window is resized.  Here are some examples::
481
482   fred.pack()                     # defaults to side = "top"
483   fred.pack(side = "left")
484   fred.pack(expand = 1)
485
486
487Packer Options
488^^^^^^^^^^^^^^
489
490For more extensive information on the packer and the options that it can take,
491see the man pages and page 183 of John Ousterhout's book.
492
493anchor
494   Anchor type.  Denotes where the packer is to place each slave in its parcel.
495
496expand
497   Boolean, ``0`` or ``1``.
498
499fill
500   Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
501
502ipadx and ipady
503   A distance - designating internal padding on each side of the slave widget.
504
505padx and pady
506   A distance - designating external padding on each side of the slave widget.
507
508side
509   Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
510
511
512Coupling Widget Variables
513^^^^^^^^^^^^^^^^^^^^^^^^^
514
515The current-value setting of some widgets (like text entry widgets) can be
516connected directly to application variables by using special options.  These
517options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
518``value``.  This connection works both ways: if the variable changes for any
519reason, the widget it's connected to will be updated to reflect the new value.
520
521Unfortunately, in the current implementation of :mod:`Tkinter` it is not
522possible to hand over an arbitrary Python variable to a widget through a
523``variable`` or ``textvariable`` option.  The only kinds of variables for which
524this works are variables that are subclassed from a class called Variable,
525defined in the :mod:`Tkinter` module.
526
527There are many useful subclasses of Variable already defined:
528:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
529:class:`BooleanVar`.  To read the current value of such a variable, call the
530:meth:`get` method on it, and to change its value you call the :meth:`set`
531method.  If you follow this protocol, the widget will always track the value of
532the variable, with no further intervention on your part.
533
534For example::
535
536   class App(Frame):
537       def __init__(self, master=None):
538           Frame.__init__(self, master)
539           self.pack()
540
541           self.entrythingy = Entry()
542           self.entrythingy.pack()
543
544           # here is the application variable
545           self.contents = StringVar()
546           # set it to some value
547           self.contents.set("this is a variable")
548           # tell the entry widget to watch this variable
549           self.entrythingy["textvariable"] = self.contents
550
551           # and here we get a callback when the user hits return.
552           # we will have the program print out the value of the
553           # application variable when the user hits return
554           self.entrythingy.bind('<Key-Return>',
555                                 self.print_contents)
556
557       def print_contents(self, event):
558           print "hi. contents of entry is now ---->", \
559                 self.contents.get()
560
561
562The Window Manager
563^^^^^^^^^^^^^^^^^^
564
565.. index:: single: window manager (widgets)
566
567In Tk, there is a utility command, ``wm``, for interacting with the window
568manager.  Options to the ``wm`` command allow you to control things like titles,
569placement, icon bitmaps, and the like.  In :mod:`Tkinter`, these commands have
570been implemented as methods on the :class:`Wm` class.  Toplevel widgets are
571subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
572directly.
573
574To get at the toplevel window that contains a given widget, you can often just
575refer to the widget's master.  Of course if the widget has been packed inside of
576a frame, the master won't represent a toplevel window.  To get at the toplevel
577window that contains an arbitrary widget, you can call the :meth:`_root` method.
578This method begins with an underscore to denote the fact that this function is
579part of the implementation, and not an interface to Tk functionality.
580
581Here are some examples of typical usage::
582
583   from Tkinter import *
584   class App(Frame):
585       def __init__(self, master=None):
586           Frame.__init__(self, master)
587           self.pack()
588
589
590   # create the application
591   myapp = App()
592
593   #
594   # here are method calls to the window manager class
595   #
596   myapp.master.title("My Do-Nothing Application")
597   myapp.master.maxsize(1000, 400)
598
599   # start the program
600   myapp.mainloop()
601
602
603Tk Option Data Types
604^^^^^^^^^^^^^^^^^^^^
605
606.. index:: single: Tk Option Data Types
607
608anchor
609   Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
610   ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
611
612bitmap
613   There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
614   ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
615   ``'warning'``.  To specify an X bitmap filename, give the full path to the file,
616   preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
617
618boolean
619   You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"`` .
620
621callback
622   This is any Python function that takes no arguments.  For example::
623
624      def print_it():
625              print "hi there"
626      fred["command"] = print_it
627
628color
629   Colors can be given as the names of X colors in the rgb.txt file, or as strings
630   representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
631   ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
632   represent any legal hex digit.  See page 160 of Ousterhout's book for details.
633
634cursor
635   The standard X cursor names from :file:`cursorfont.h` can be used, without the
636   ``XC_`` prefix.  For example to get a hand cursor (:const:`XC_hand2`), use the
637   string ``"hand2"``.  You can also specify a bitmap and mask file of your own.
638   See page 179 of Ousterhout's book.
639
640distance
641   Screen distances can be specified in either pixels or absolute distances.
642   Pixels are given as numbers and absolute distances as strings, with the trailing
643   character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
644   millimetres, ``p`` for printer's points.  For example, 3.5 inches is expressed
645   as ``"3.5i"``.
646
647font
648   Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
649   positive numbers are measured in points; sizes with negative numbers are
650   measured in pixels.
651
652geometry
653   This is a string of the form ``widthxheight``, where width and height are
654   measured in pixels for most widgets (in characters for widgets displaying text).
655   For example: ``fred["geometry"] = "200x100"``.
656
657justify
658   Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
659   ``"fill"``.
660
661region
662   This is a string with four space-delimited elements, each of which is a legal
663   distance (see above).  For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
664   ``"3c 2c 4c 10.43c"``  are all legal regions.
665
666relief
667   Determines what the border style of a widget will be.  Legal values are:
668   ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
669
670scrollcommand
671   This is almost always the :meth:`set` method of some scrollbar widget, but can
672   be any widget method that takes a single argument.   Refer to the file
673   :file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
674   distribution for an example.
675
676wrap:
677   Must be one of: ``"none"``, ``"char"``, or ``"word"``.
678
679
680Bindings and Events
681^^^^^^^^^^^^^^^^^^^
682
683.. index::
684   single: bind (widgets)
685   single: events (widgets)
686
687The bind method from the widget command allows you to watch for certain events
688and to have a callback function trigger when that event type occurs.  The form
689of the bind method is::
690
691   def bind(self, sequence, func, add=''):
692
693where:
694
695sequence
696   is a string that denotes the target kind of event.  (See the bind man page and
697   page 201 of John Ousterhout's book for details).
698
699func
700   is a Python function, taking one argument, to be invoked when the event occurs.
701   An Event instance will be passed as the argument. (Functions deployed this way
702   are commonly known as *callbacks*.)
703
704add
705   is optional, either ``''`` or ``'+'``.  Passing an empty string denotes that
706   this binding is to replace any other bindings that this event is associated
707   with.  Passing a ``'+'`` means that this function is to be added to the list
708   of functions bound to this event type.
709
710For example::
711
712   def turnRed(self, event):
713       event.widget["activeforeground"] = "red"
714
715   self.button.bind("<Enter>", self.turnRed)
716
717Notice how the widget field of the event is being accessed in the
718:meth:`turnRed` callback.  This field contains the widget that caught the X
719event.  The following table lists the other event fields you can access, and how
720they are denoted in Tk, which can be useful when referring to the Tk man pages.
721::
722
723   Tk      Tkinter Event Field             Tk      Tkinter Event Field
724   --      -------------------             --      -------------------
725   %f      focus                           %A      char
726   %h      height                          %E      send_event
727   %k      keycode                         %K      keysym
728   %s      state                           %N      keysym_num
729   %t      time                            %T      type
730   %w      width                           %W      widget
731   %x      x                               %X      x_root
732   %y      y                               %Y      y_root
733
734
735The index Parameter
736^^^^^^^^^^^^^^^^^^^
737
738A number of widgets require"index" parameters to be passed.  These are used to
739point at a specific place in a Text widget, or to particular characters in an
740Entry widget, or to particular menu items in a Menu widget.
741
742Entry widget indexes (index, view index, etc.)
743   Entry widgets have options that refer to character positions in the text being
744   displayed.  You can use these :mod:`Tkinter` functions to access these special
745   points in text widgets:
746
747   AtEnd()
748      refers to the last position in the text
749
750   AtInsert()
751      refers to the point where the text cursor is
752
753   AtSelFirst()
754      indicates the beginning point of the selected text
755
756   AtSelLast()
757      denotes the last point of the selected text and finally
758
759   At(x[, y])
760      refers to the character at pixel location *x*, *y* (with *y* not used in the
761      case of a text entry widget, which contains a single line of text).
762
763Text widget indexes
764   The index notation for Text widgets is very rich and is best described in the Tk
765   man pages.
766
767Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
768   Some options and methods for menus manipulate specific menu entries. Anytime a
769   menu index is needed for an option or a parameter, you may pass in:
770
771   * an integer which refers to the numeric position of the entry in the widget,
772     counted from the top, starting with 0;
773
774   * the string ``'active'``, which refers to the menu position that is currently
775     under the cursor;
776
777   * the string ``"last"`` which refers to the last menu item;
778
779   * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
780     as a y pixel coordinate in the menu's coordinate system;
781
782   * the string ``"none"``, which indicates no menu entry at all, most often used
783     with menu.activate() to deactivate all entries, and finally,
784
785   * a text string that is pattern matched against the label of the menu entry, as
786     scanned from the top of the menu to the bottom.  Note that this index type is
787     considered after all the others, which means that matches for menu items
788     labelled ``last``, ``active``, or ``none`` may be interpreted as the above
789     literals, instead.
790
791
792Images
793^^^^^^
794
795Bitmap/Pixelmap images can be created through the subclasses of
796:class:`Tkinter.Image`:
797
798* :class:`BitmapImage` can be used for X11 bitmap data.
799
800* :class:`PhotoImage` can be used for GIF and PPM/PGM color bitmaps.
801
802Either type of image is created through either the ``file`` or the ``data``
803option (other options are available as well).
804
805The image object can then be used wherever an ``image`` option is supported by
806some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
807reference to the image. When the last Python reference to the image object is
808deleted, the image data is deleted as well, and Tk will display an empty box
809wherever the image was used.
810