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