blob: 377694f8640f9af44a86cf85e3eef9280365d274 [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
Alexander Belopolskyc02cc272010-07-27 14:16:32 +000012is maintained at ActiveState.) You can check that :mod:`tkinter` is properly
13installed on your system by running ``python -m tkinter`` from the command line;
14this should open a window demonstrating a simple Tk interface.
Georg Brandl116aa622007-08-15 14:28:22 +000015
Georg Brandl116aa622007-08-15 14:28:22 +000016.. seealso::
17
18 `Python Tkinter Resources <http://www.python.org/topics/tkinter/>`_
19 The Python Tkinter Topic Guide provides a great deal of information on using Tk
20 from Python and links to other sources of information on Tk.
21
Andrew Svetlove708a8a2012-07-26 17:02:57 +030022 `TKDocs <http://www.tkdocs.com/>`_
23 Extensive tutorial plus friendlier widget pages for some of the widgets.
24
25 `Tkinter reference: a GUI for Python <http://infohost.nmt.edu/tcc/help/pubs/tkinter/>`_
26 On-line reference material.
27
28 `Tkinter docs from effbot <http://effbot.org/tkinterbook/>`_
29 Online reference for tkinter supported by effbot.org.
30
31 `Tcl/Tk manual <http://www.tcl.tk/man/tcl8.5/>`_
32 Official manual for the latest tcl/tk version.
33
34 `Programming Python <http://www.amazon.com/Programming-Python-Mark-Lutz/dp/0596158106/>`_
35 Book by Mark Lutz, has excellent coverage of Tkinter.
36
37 `Modern Tkinter for Busy Python Developers <http://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/>`_
38 Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.
39
Georg Brandl116aa622007-08-15 14:28:22 +000040 `An Introduction to Tkinter <http://www.pythonware.com/library/an-introduction-to-tkinter.htm>`_
41 Fredrik Lundh's on-line reference material.
42
Georg Brandl116aa622007-08-15 14:28:22 +000043 `Python and Tkinter Programming <http://www.amazon.com/exec/obidos/ASIN/1884777813>`_
44 The book by John Grayson (ISBN 1-884777-81-3).
45
46
47Tkinter Modules
48---------------
49
Ezio Melotti1a263ad2010-03-14 09:51:37 +000050Most of the time, :mod:`tkinter` is all you really need, but a number of
51additional modules are available as well. The Tk interface is located in a
Georg Brandl116aa622007-08-15 14:28:22 +000052binary module named :mod:`_tkinter`. This module contains the low-level
53interface to Tk, and should never be used directly by application programmers.
54It is usually a shared library (or DLL), but might in some cases be statically
55linked with the Python interpreter.
56
Georg Brandlac6060c2008-05-17 18:44:45 +000057In addition to the Tk interface module, :mod:`tkinter` includes a number of
Georg Brandl48310cd2009-01-03 21:18:54 +000058Python modules, :mod:`tkinter.constants` being one of the most important.
Georg Brandlac6060c2008-05-17 18:44:45 +000059Importing :mod:`tkinter` will automatically import :mod:`tkinter.constants`,
60so, usually, to use Tkinter all you need is a simple import statement::
Georg Brandl116aa622007-08-15 14:28:22 +000061
Georg Brandlac6060c2008-05-17 18:44:45 +000062 import tkinter
Georg Brandl116aa622007-08-15 14:28:22 +000063
64Or, more often::
65
Georg Brandlac6060c2008-05-17 18:44:45 +000066 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +000067
68
69.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
70
71 The :class:`Tk` class is instantiated without arguments. This creates a toplevel
72 widget of Tk which usually is the main window of an application. Each instance
73 has its own associated Tcl interpreter.
74
Christian Heimes5b5e81c2007-12-31 16:14:33 +000075 .. FIXME: The following keyword arguments are currently recognized:
Georg Brandl116aa622007-08-15 14:28:22 +000076
Georg Brandl116aa622007-08-15 14:28:22 +000077
78.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
79
80 The :func:`Tcl` function is a factory function which creates an object much like
81 that created by the :class:`Tk` class, except that it does not initialize the Tk
82 subsystem. This is most often useful when driving the Tcl interpreter in an
83 environment where one doesn't want to create extraneous toplevel windows, or
84 where one cannot (such as Unix/Linux systems without an X server). An object
85 created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
86 subsystem initialized) by calling its :meth:`loadtk` method.
87
Georg Brandl116aa622007-08-15 14:28:22 +000088
89Other modules that provide Tk support include:
90
Georg Brandlac6060c2008-05-17 18:44:45 +000091:mod:`tkinter.scrolledtext`
Georg Brandl116aa622007-08-15 14:28:22 +000092 Text widget with a vertical scroll bar built in.
93
Georg Brandlac6060c2008-05-17 18:44:45 +000094:mod:`tkinter.colorchooser`
Georg Brandl116aa622007-08-15 14:28:22 +000095 Dialog to let the user choose a color.
96
Georg Brandlac6060c2008-05-17 18:44:45 +000097:mod:`tkinter.commondialog`
Georg Brandl116aa622007-08-15 14:28:22 +000098 Base class for the dialogs defined in the other modules listed here.
99
Georg Brandlac6060c2008-05-17 18:44:45 +0000100:mod:`tkinter.filedialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000101 Common dialogs to allow the user to specify a file to open or save.
102
Georg Brandlac6060c2008-05-17 18:44:45 +0000103:mod:`tkinter.font`
Georg Brandl116aa622007-08-15 14:28:22 +0000104 Utilities to help work with fonts.
105
Georg Brandlac6060c2008-05-17 18:44:45 +0000106:mod:`tkinter.messagebox`
Georg Brandl116aa622007-08-15 14:28:22 +0000107 Access to standard Tk dialog boxes.
108
Georg Brandlac6060c2008-05-17 18:44:45 +0000109:mod:`tkinter.simpledialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000110 Basic dialogs and convenience functions.
111
Georg Brandlac6060c2008-05-17 18:44:45 +0000112:mod:`tkinter.dnd`
Georg Brandl48310cd2009-01-03 21:18:54 +0000113 Drag-and-drop support for :mod:`tkinter`. This is experimental and should
Georg Brandlac6060c2008-05-17 18:44:45 +0000114 become deprecated when it is replaced with the Tk DND.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Georg Brandl23d11d32008-09-21 07:50:52 +0000116:mod:`turtle`
Georg Brandl116aa622007-08-15 14:28:22 +0000117 Turtle graphics in a Tk window.
118
119
120Tkinter Life Preserver
121----------------------
122
123.. sectionauthor:: Matt Conway
124
125
126This section is not designed to be an exhaustive tutorial on either Tk or
127Tkinter. Rather, it is intended as a stop gap, providing some introductory
128orientation on the system.
129
Georg Brandl116aa622007-08-15 14:28:22 +0000130Credits:
131
Georg Brandl116aa622007-08-15 14:28:22 +0000132* Tk was written by John Ousterhout while at Berkeley.
133
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000134* Tkinter was written by Steen Lumholt and Guido van Rossum.
135
Georg Brandl116aa622007-08-15 14:28:22 +0000136* This Life Preserver was written by Matt Conway at the University of Virginia.
137
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000138* The HTML rendering, and some liberal editing, was produced from a FrameMaker
Georg Brandl116aa622007-08-15 14:28:22 +0000139 version by Ken Manheimer.
140
141* Fredrik Lundh elaborated and revised the class interface descriptions, to get
142 them current with Tk 4.2.
143
144* Mike Clarkson converted the documentation to LaTeX, and compiled the User
145 Interface chapter of the reference manual.
146
147
148How To Use This Section
149^^^^^^^^^^^^^^^^^^^^^^^
150
151This section is designed in two parts: the first half (roughly) covers
152background material, while the second half can be taken to the keyboard as a
153handy reference.
154
155When trying to answer questions of the form "how do I do blah", it is often best
156to find out how to do"blah" in straight Tk, and then convert this back into the
Georg Brandlac6060c2008-05-17 18:44:45 +0000157corresponding :mod:`tkinter` call. Python programmers can often guess at the
Georg Brandl116aa622007-08-15 14:28:22 +0000158correct Python command by looking at the Tk documentation. This means that in
159order to use Tkinter, you will have to know a little bit about Tk. This document
160can't fulfill that role, so the best we can do is point you to the best
161documentation that exists. Here are some hints:
162
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000163* The authors strongly suggest getting a copy of the Tk man pages.
164 Specifically, the man pages in the ``manN`` directory are most useful.
165 The ``man3`` man pages describe the C interface to the Tk library and thus
166 are not especially helpful for script writers.
Georg Brandl116aa622007-08-15 14:28:22 +0000167
168* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
169 Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
170 the novice. The book is not exhaustive, and for many details it defers to the
171 man pages.
172
Georg Brandl48310cd2009-01-03 21:18:54 +0000173* :file:`tkinter/__init__.py` is a last resort for most, but can be a good
Georg Brandlac6060c2008-05-17 18:44:45 +0000174 place to go when nothing else makes sense.
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176
177.. seealso::
178
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000179 `Tcl/Tk 8.6 man pages <http://www.tcl.tk/man/tcl8.6/>`_
180 The Tcl/Tk manual on www.tcl.tk.
181
Georg Brandl116aa622007-08-15 14:28:22 +0000182 `ActiveState Tcl Home Page <http://tcl.activestate.com/>`_
183 The Tk/Tcl development is largely taking place at ActiveState.
184
185 `Tcl and the Tk Toolkit <http://www.amazon.com/exec/obidos/ASIN/020163337X>`_
186 The book by John Ousterhout, the inventor of Tcl .
187
188 `Practical Programming in Tcl and Tk <http://www.amazon.com/exec/obidos/ASIN/0130220280>`_
189 Brent Welch's encyclopedic book.
190
191
192A Simple Hello World Program
193^^^^^^^^^^^^^^^^^^^^^^^^^^^^
194
Georg Brandl116aa622007-08-15 14:28:22 +0000195::
196
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700197 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700199 class Application(tk.Frame):
200 def __init__(self, master=None):
201 tk.Frame.__init__(self, master)
202 self.pack()
203 self.createWidgets()
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700205 def createWidgets(self):
206 self.hi_there = tk.Button(self)
207 self.hi_there["text"] = "Hello World\n(click me)"
208 self.hi_there["command"] = self.say_hi
209 self.hi_there.pack(side="top")
Georg Brandl116aa622007-08-15 14:28:22 +0000210
Andrew Svetlov1d561792012-03-25 11:44:59 +0300211 self.QUIT = tk.Button(self, text="QUIT", fg="red",
212 command=root.destroy)
213 self.QUIT.pack(side="bottom")
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700215 def say_hi(self):
216 print("hi there, everyone!")
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700218 root = tk.Tk()
219 app = Application(master=root)
220 app.mainloop()
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222
223A (Very) Quick Look at Tcl/Tk
224-----------------------------
225
226The class hierarchy looks complicated, but in actual practice, application
227programmers almost always refer to the classes at the very bottom of the
228hierarchy.
229
Georg Brandl116aa622007-08-15 14:28:22 +0000230Notes:
231
232* These classes are provided for the purposes of organizing certain functions
233 under one namespace. They aren't meant to be instantiated independently.
234
235* The :class:`Tk` class is meant to be instantiated only once in an application.
236 Application programmers need not instantiate one explicitly, the system creates
237 one whenever any of the other classes are instantiated.
238
239* The :class:`Widget` class is not meant to be instantiated, it is meant only
240 for subclassing to make "real" widgets (in C++, this is called an 'abstract
241 class').
242
243To make use of this reference material, there will be times when you will need
244to know how to read short passages of Tk and how to identify the various parts
245of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
Georg Brandlac6060c2008-05-17 18:44:45 +0000246:mod:`tkinter` equivalents of what's below.)
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
249of tokens separated by spaces. A Tk widget is just its *class*, the *options*
250that help configure it, and the *actions* that make it do useful things.
251
252To make a widget in Tk, the command is always of the form::
253
254 classCommand newPathname options
255
256*classCommand*
257 denotes which kind of widget to make (a button, a label, a menu...)
258
259*newPathname*
260 is the new name for this widget. All names in Tk must be unique. To help
261 enforce this, widgets in Tk are named with *pathnames*, just like files in a
262 file system. The top level widget, the *root*, is called ``.`` (period) and
263 children are delimited by more periods. For example,
264 ``.myApp.controlPanel.okButton`` might be the name of a widget.
265
266*options*
267 configure the widget's appearance and in some cases, its behavior. The options
268 come in the form of a list of flags and values. Flags are preceded by a '-',
269 like Unix shell command flags, and values are put in quotes if they are more
270 than one word.
271
272For example::
273
274 button .fred -fg red -text "hi there"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000275 ^ ^ \______________________/
Georg Brandl116aa622007-08-15 14:28:22 +0000276 | | |
277 class new options
278 command widget (-opt val -opt val ...)
279
280Once created, the pathname to the widget becomes a new command. This new
281*widget command* is the programmer's handle for getting the new widget to
282perform some *action*. In C, you'd express this as someAction(fred,
283someOptions), in C++, you would express this as fred.someAction(someOptions),
284and in Tk, you say::
285
Georg Brandl48310cd2009-01-03 21:18:54 +0000286 .fred someAction someOptions
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288Note that the object name, ``.fred``, starts with a dot.
289
290As you'd expect, the legal values for *someAction* will depend on the widget's
291class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
292does not work if fred is a label (disabling of labels is not supported in Tk).
293
294The legal values of *someOptions* is action dependent. Some actions, like
295``disable``, require no arguments, others, like a text-entry box's ``delete``
296command, would need arguments to specify what range of text to delete.
297
298
299.. _tkinter-basic-mapping:
300
301Mapping Basic Tk into Tkinter
302-----------------------------
303
304Class commands in Tk correspond to class constructors in Tkinter. ::
305
306 button .fred =====> fred = Button()
307
308The master of an object is implicit in the new name given to it at creation
309time. In Tkinter, masters are specified explicitly. ::
310
311 button .panel.fred =====> fred = Button(panel)
312
313The configuration options in Tk are given in lists of hyphened tags followed by
314values. In Tkinter, options are specified as keyword-arguments in the instance
315constructor, and keyword-args for configure calls or as instance indices, in
316dictionary style, for established instances. See section
317:ref:`tkinter-setting-options` on setting options. ::
318
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000319 button .fred -fg red =====> fred = Button(panel, fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000320 .fred configure -fg red =====> fred["fg"] = red
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000321 OR ==> fred.config(fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323In Tk, to perform an action on a widget, use the widget name as a command, and
324follow it with an action name, possibly with arguments (options). In Tkinter,
325you call methods on the class instance to invoke actions on the widget. The
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000326actions (methods) that a given widget can perform are listed in
327:file:`tkinter/__init__.py`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329 .fred invoke =====> fred.invoke()
330
331To give a widget to the packer (geometry manager), you call pack with optional
332arguments. In Tkinter, the Pack class holds all this functionality, and the
333various forms of the pack command are implemented as methods. All widgets in
Georg Brandlac6060c2008-05-17 18:44:45 +0000334:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
Georg Brandl48310cd2009-01-03 21:18:54 +0000335methods. See the :mod:`tkinter.tix` module documentation for additional
Georg Brandlac6060c2008-05-17 18:44:45 +0000336information on the Form geometry manager. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000337
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000338 pack .fred -side left =====> fred.pack(side="left")
Georg Brandl116aa622007-08-15 14:28:22 +0000339
340
341How Tk and Tkinter are Related
342------------------------------
343
Georg Brandl116aa622007-08-15 14:28:22 +0000344From the top down:
345
346Your App Here (Python)
Georg Brandlac6060c2008-05-17 18:44:45 +0000347 A Python application makes a :mod:`tkinter` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Georg Brandlac6060c2008-05-17 18:44:45 +0000349tkinter (Python Package)
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000350 This call (say, for example, creating a button widget), is implemented in
351 the :mod:`tkinter` package, which is written in Python. This Python
352 function will parse the commands and the arguments and convert them into a
353 form that makes them look as if they had come from a Tk script instead of
354 a Python script.
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000356_tkinter (C)
Georg Brandl116aa622007-08-15 14:28:22 +0000357 These commands and their arguments will be passed to a C function in the
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000358 :mod:`_tkinter` - note the underscore - extension module.
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360Tk Widgets (C and Tcl)
361 This C function is able to make calls into other C modules, including the C
362 functions that make up the Tk library. Tk is implemented in C and some Tcl.
363 The Tcl part of the Tk widgets is used to bind certain default behaviors to
Georg Brandlac6060c2008-05-17 18:44:45 +0000364 widgets, and is executed once at the point where the Python :mod:`tkinter`
365 package is imported. (The user never sees this stage).
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367Tk (C)
368 The Tk part of the Tk Widgets implement the final mapping to ...
369
370Xlib (C)
371 the Xlib library to draw graphics on the screen.
372
373
374Handy Reference
375---------------
376
377
378.. _tkinter-setting-options:
379
380Setting Options
381^^^^^^^^^^^^^^^
382
383Options control things like the color and border width of a widget. Options can
384be set in three ways:
385
386At object creation time, using keyword arguments
387 ::
388
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000389 fred = Button(self, fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391After object creation, treating the option name like a dictionary index
392 ::
393
394 fred["fg"] = "red"
395 fred["bg"] = "blue"
396
397Use the config() method to update multiple attrs subsequent to object creation
398 ::
399
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000400 fred.config(fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402For a complete explanation of a given option and its behavior, see the Tk man
403pages for the widget in question.
404
405Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
406for each widget. The former is a list of options that are common to many
407widgets, the latter are the options that are idiosyncratic to that particular
408widget. The Standard Options are documented on the :manpage:`options(3)` man
409page.
410
411No distinction between standard and widget-specific options is made in this
412document. Some options don't apply to some kinds of widgets. Whether a given
413widget responds to a particular option depends on the class of the widget;
414buttons have a ``command`` option, labels do not.
415
416The options supported by a given widget are listed in that widget's man page, or
417can be queried at runtime by calling the :meth:`config` method without
418arguments, or by calling the :meth:`keys` method on that widget. The return
419value of these calls is a dictionary whose key is the name of the option as a
420string (for example, ``'relief'``) and whose values are 5-tuples.
421
422Some options, like ``bg`` are synonyms for common options with long names
423(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
424of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
425back will contain the name of the synonym and the "real" option (such as
426``('bg', 'background')``).
427
428+-------+---------------------------------+--------------+
429| Index | Meaning | Example |
430+=======+=================================+==============+
431| 0 | option name | ``'relief'`` |
432+-------+---------------------------------+--------------+
433| 1 | option name for database lookup | ``'relief'`` |
434+-------+---------------------------------+--------------+
435| 2 | option class for database | ``'Relief'`` |
436| | lookup | |
437+-------+---------------------------------+--------------+
438| 3 | default value | ``'raised'`` |
439+-------+---------------------------------+--------------+
440| 4 | current value | ``'groove'`` |
441+-------+---------------------------------+--------------+
442
443Example::
444
Collin Winterc79461b2007-09-01 23:34:30 +0000445 >>> print(fred.config())
Georg Brandl116aa622007-08-15 14:28:22 +0000446 {'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
447
448Of course, the dictionary printed will include all the options available and
449their values. This is meant only as an example.
450
451
452The Packer
453^^^^^^^^^^
454
455.. index:: single: packing (widgets)
456
Georg Brandl116aa622007-08-15 14:28:22 +0000457The packer is one of Tk's geometry-management mechanisms. Geometry managers
458are used to specify the relative positioning of the positioning of widgets
459within their container - their mutual *master*. In contrast to the more
460cumbersome *placer* (which is used less commonly, and we do not cover here), the
461packer takes qualitative relationship specification - *above*, *to the left of*,
462*filling*, etc - and works everything out to determine the exact placement
463coordinates for you.
464
Georg Brandl116aa622007-08-15 14:28:22 +0000465The size of any *master* widget is determined by the size of the "slave widgets"
466inside. The packer is used to control where slave widgets appear inside the
467master into which they are packed. You can pack widgets into frames, and frames
468into other frames, in order to achieve the kind of layout you desire.
469Additionally, the arrangement is dynamically adjusted to accommodate incremental
470changes to the configuration, once it is packed.
471
472Note that widgets do not appear until they have had their geometry specified
473with a geometry manager. It's a common early mistake to leave out the geometry
474specification, and then be surprised when the widget is created but nothing
475appears. A widget will appear only after it has had, for example, the packer's
476:meth:`pack` method applied to it.
477
478The pack() method can be called with keyword-option/value pairs that control
479where the widget is to appear within its container, and how it is to behave when
480the main application window is resized. Here are some examples::
481
482 fred.pack() # defaults to side = "top"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000483 fred.pack(side="left")
484 fred.pack(expand=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000485
486
487Packer Options
488^^^^^^^^^^^^^^
489
490For more extensive information on the packer and the options that it can take,
491see the man pages and page 183 of John Ousterhout's book.
492
Georg Brandl48310cd2009-01-03 21:18:54 +0000493anchor
Georg Brandl116aa622007-08-15 14:28:22 +0000494 Anchor type. Denotes where the packer is to place each slave in its parcel.
495
496expand
497 Boolean, ``0`` or ``1``.
498
499fill
500 Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
501
502ipadx and ipady
503 A distance - designating internal padding on each side of the slave widget.
504
505padx and pady
506 A distance - designating external padding on each side of the slave widget.
507
508side
509 Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
510
511
512Coupling Widget Variables
513^^^^^^^^^^^^^^^^^^^^^^^^^
514
515The current-value setting of some widgets (like text entry widgets) can be
516connected directly to application variables by using special options. These
517options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
518``value``. This connection works both ways: if the variable changes for any
519reason, the widget it's connected to will be updated to reflect the new value.
520
Georg Brandlac6060c2008-05-17 18:44:45 +0000521Unfortunately, in the current implementation of :mod:`tkinter` it is not
Georg Brandl116aa622007-08-15 14:28:22 +0000522possible to hand over an arbitrary Python variable to a widget through a
523``variable`` or ``textvariable`` option. The only kinds of variables for which
524this works are variables that are subclassed from a class called Variable,
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000525defined in :mod:`tkinter`.
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527There are many useful subclasses of Variable already defined:
528:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
529:class:`BooleanVar`. To read the current value of such a variable, call the
Georg Brandl502d9a52009-07-26 15:02:41 +0000530:meth:`get` method on it, and to change its value you call the :meth:`!set`
Georg Brandl116aa622007-08-15 14:28:22 +0000531method. If you follow this protocol, the widget will always track the value of
532the variable, with no further intervention on your part.
533
534For example::
535
536 class App(Frame):
537 def __init__(self, master=None):
538 Frame.__init__(self, master)
539 self.pack()
540
541 self.entrythingy = Entry()
542 self.entrythingy.pack()
543
544 # here is the application variable
545 self.contents = StringVar()
546 # set it to some value
547 self.contents.set("this is a variable")
548 # tell the entry widget to watch this variable
549 self.entrythingy["textvariable"] = self.contents
550
551 # and here we get a callback when the user hits return.
552 # we will have the program print out the value of the
553 # application variable when the user hits return
554 self.entrythingy.bind('<Key-Return>',
555 self.print_contents)
556
557 def print_contents(self, event):
Collin Winterc79461b2007-09-01 23:34:30 +0000558 print("hi. contents of entry is now ---->",
559 self.contents.get())
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561
562The Window Manager
563^^^^^^^^^^^^^^^^^^
564
565.. index:: single: window manager (widgets)
566
Georg Brandl116aa622007-08-15 14:28:22 +0000567In Tk, there is a utility command, ``wm``, for interacting with the window
568manager. Options to the ``wm`` command allow you to control things like titles,
Georg Brandlac6060c2008-05-17 18:44:45 +0000569placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
Georg Brandl116aa622007-08-15 14:28:22 +0000570been implemented as methods on the :class:`Wm` class. Toplevel widgets are
571subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
572directly.
573
574To get at the toplevel window that contains a given widget, you can often just
575refer to the widget's master. Of course if the widget has been packed inside of
576a frame, the master won't represent a toplevel window. To get at the toplevel
577window that contains an arbitrary widget, you can call the :meth:`_root` method.
578This method begins with an underscore to denote the fact that this function is
579part of the implementation, and not an interface to Tk functionality.
580
Georg Brandl116aa622007-08-15 14:28:22 +0000581Here are some examples of typical usage::
582
Georg Brandlac6060c2008-05-17 18:44:45 +0000583 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +0000584 class App(Frame):
585 def __init__(self, master=None):
586 Frame.__init__(self, master)
587 self.pack()
588
589
590 # create the application
591 myapp = App()
592
593 #
594 # here are method calls to the window manager class
595 #
596 myapp.master.title("My Do-Nothing Application")
597 myapp.master.maxsize(1000, 400)
598
599 # start the program
600 myapp.mainloop()
601
602
603Tk Option Data Types
604^^^^^^^^^^^^^^^^^^^^
605
606.. index:: single: Tk Option Data Types
607
Georg Brandl116aa622007-08-15 14:28:22 +0000608anchor
609 Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
610 ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
611
612bitmap
613 There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
614 ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
615 ``'warning'``. To specify an X bitmap filename, give the full path to the file,
616 preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
617
618boolean
619 You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"`` .
620
621callback
622 This is any Python function that takes no arguments. For example::
623
624 def print_it():
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000625 print("hi there")
Georg Brandl116aa622007-08-15 14:28:22 +0000626 fred["command"] = print_it
627
628color
629 Colors can be given as the names of X colors in the rgb.txt file, or as strings
630 representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
631 ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
632 represent any legal hex digit. See page 160 of Ousterhout's book for details.
633
634cursor
635 The standard X cursor names from :file:`cursorfont.h` can be used, without the
636 ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
637 string ``"hand2"``. You can also specify a bitmap and mask file of your own.
638 See page 179 of Ousterhout's book.
639
640distance
641 Screen distances can be specified in either pixels or absolute distances.
642 Pixels are given as numbers and absolute distances as strings, with the trailing
643 character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
644 millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
645 as ``"3.5i"``.
646
647font
648 Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
649 positive numbers are measured in points; sizes with negative numbers are
650 measured in pixels.
651
652geometry
653 This is a string of the form ``widthxheight``, where width and height are
654 measured in pixels for most widgets (in characters for widgets displaying text).
655 For example: ``fred["geometry"] = "200x100"``.
656
657justify
658 Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
659 ``"fill"``.
660
661region
662 This is a string with four space-delimited elements, each of which is a legal
663 distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
664 ``"3c 2c 4c 10.43c"`` are all legal regions.
665
666relief
667 Determines what the border style of a widget will be. Legal values are:
668 ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
669
670scrollcommand
Georg Brandl502d9a52009-07-26 15:02:41 +0000671 This is almost always the :meth:`!set` method of some scrollbar widget, but can
Georg Brandl59b44722010-12-30 22:12:40 +0000672 be any widget method that takes a single argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674wrap:
675 Must be one of: ``"none"``, ``"char"``, or ``"word"``.
676
677
678Bindings and Events
679^^^^^^^^^^^^^^^^^^^
680
681.. index::
682 single: bind (widgets)
683 single: events (widgets)
684
Georg Brandl116aa622007-08-15 14:28:22 +0000685The bind method from the widget command allows you to watch for certain events
686and to have a callback function trigger when that event type occurs. The form
687of the bind method is::
688
689 def bind(self, sequence, func, add=''):
690
691where:
692
693sequence
694 is a string that denotes the target kind of event. (See the bind man page and
695 page 201 of John Ousterhout's book for details).
696
697func
698 is a Python function, taking one argument, to be invoked when the event occurs.
699 An Event instance will be passed as the argument. (Functions deployed this way
700 are commonly known as *callbacks*.)
701
702add
703 is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
704 this binding is to replace any other bindings that this event is associated
705 with. Passing a ``'+'`` means that this function is to be added to the list
706 of functions bound to this event type.
707
708For example::
709
710 def turnRed(self, event):
711 event.widget["activeforeground"] = "red"
712
713 self.button.bind("<Enter>", self.turnRed)
714
715Notice how the widget field of the event is being accessed in the
716:meth:`turnRed` callback. This field contains the widget that caught the X
717event. The following table lists the other event fields you can access, and how
718they are denoted in Tk, which can be useful when referring to the Tk man pages.
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000720+----+---------------------+----+---------------------+
721| Tk | Tkinter Event Field | Tk | Tkinter Event Field |
722+====+=====================+====+=====================+
723| %f | focus | %A | char |
724+----+---------------------+----+---------------------+
725| %h | height | %E | send_event |
726+----+---------------------+----+---------------------+
727| %k | keycode | %K | keysym |
728+----+---------------------+----+---------------------+
729| %s | state | %N | keysym_num |
730+----+---------------------+----+---------------------+
731| %t | time | %T | type |
732+----+---------------------+----+---------------------+
733| %w | width | %W | widget |
734+----+---------------------+----+---------------------+
735| %x | x | %X | x_root |
736+----+---------------------+----+---------------------+
737| %y | y | %Y | y_root |
738+----+---------------------+----+---------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000739
740
741The index Parameter
742^^^^^^^^^^^^^^^^^^^
743
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000744A number of widgets require "index" parameters to be passed. These are used to
Georg Brandl116aa622007-08-15 14:28:22 +0000745point at a specific place in a Text widget, or to particular characters in an
746Entry widget, or to particular menu items in a Menu widget.
747
Georg Brandl116aa622007-08-15 14:28:22 +0000748Entry widget indexes (index, view index, etc.)
749 Entry widgets have options that refer to character positions in the text being
Georg Brandlac6060c2008-05-17 18:44:45 +0000750 displayed. You can use these :mod:`tkinter` functions to access these special
Georg Brandl116aa622007-08-15 14:28:22 +0000751 points in text widgets:
752
Georg Brandl116aa622007-08-15 14:28:22 +0000753Text widget indexes
754 The index notation for Text widgets is very rich and is best described in the Tk
755 man pages.
756
757Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
758 Some options and methods for menus manipulate specific menu entries. Anytime a
759 menu index is needed for an option or a parameter, you may pass in:
760
761 * an integer which refers to the numeric position of the entry in the widget,
762 counted from the top, starting with 0;
763
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000764 * the string ``"active"``, which refers to the menu position that is currently
Georg Brandl116aa622007-08-15 14:28:22 +0000765 under the cursor;
766
767 * the string ``"last"`` which refers to the last menu item;
768
769 * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
770 as a y pixel coordinate in the menu's coordinate system;
771
772 * the string ``"none"``, which indicates no menu entry at all, most often used
773 with menu.activate() to deactivate all entries, and finally,
774
775 * a text string that is pattern matched against the label of the menu entry, as
776 scanned from the top of the menu to the bottom. Note that this index type is
777 considered after all the others, which means that matches for menu items
778 labelled ``last``, ``active``, or ``none`` may be interpreted as the above
779 literals, instead.
780
781
782Images
783^^^^^^
784
785Bitmap/Pixelmap images can be created through the subclasses of
Georg Brandlac6060c2008-05-17 18:44:45 +0000786:class:`tkinter.Image`:
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788* :class:`BitmapImage` can be used for X11 bitmap data.
789
790* :class:`PhotoImage` can be used for GIF and PPM/PGM color bitmaps.
791
792Either type of image is created through either the ``file`` or the ``data``
793option (other options are available as well).
794
795The image object can then be used wherever an ``image`` option is supported by
796some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
797reference to the image. When the last Python reference to the image object is
798deleted, the image data is deleted as well, and Tk will display an empty box
799wherever the image was used.