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