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