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