blob: 40e97bf0f10b297a673bf8467049398f1119afc1 [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
Zachary Ware08863992014-03-18 09:19:18 -050018 `Python Tkinter Resources <https://wiki.python.org/moin/TkInter>`_
Georg Brandl116aa622007-08-15 14:28:22 +000019 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
Georg Brandlb7354a62014-10-29 10:57:37 +010025 `Tkinter reference: a GUI for Python <http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030026 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 `Python and Tkinter Programming <http://www.amazon.com/exec/obidos/ASIN/1884777813>`_
41 The book by John Grayson (ISBN 1-884777-81-3).
42
43
44Tkinter Modules
45---------------
46
Ezio Melotti1a263ad2010-03-14 09:51:37 +000047Most of the time, :mod:`tkinter` is all you really need, but a number of
48additional modules are available as well. The Tk interface is located in a
Georg Brandl116aa622007-08-15 14:28:22 +000049binary module named :mod:`_tkinter`. This module contains the low-level
50interface to Tk, and should never be used directly by application programmers.
51It is usually a shared library (or DLL), but might in some cases be statically
52linked with the Python interpreter.
53
Georg Brandlac6060c2008-05-17 18:44:45 +000054In addition to the Tk interface module, :mod:`tkinter` includes a number of
Georg Brandl48310cd2009-01-03 21:18:54 +000055Python modules, :mod:`tkinter.constants` being one of the most important.
Georg Brandlac6060c2008-05-17 18:44:45 +000056Importing :mod:`tkinter` will automatically import :mod:`tkinter.constants`,
57so, usually, to use Tkinter all you need is a simple import statement::
Georg Brandl116aa622007-08-15 14:28:22 +000058
Georg Brandlac6060c2008-05-17 18:44:45 +000059 import tkinter
Georg Brandl116aa622007-08-15 14:28:22 +000060
61Or, more often::
62
Georg Brandlac6060c2008-05-17 18:44:45 +000063 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +000064
65
66.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
67
68 The :class:`Tk` class is instantiated without arguments. This creates a toplevel
69 widget of Tk which usually is the main window of an application. Each instance
70 has its own associated Tcl interpreter.
71
Christian Heimes5b5e81c2007-12-31 16:14:33 +000072 .. FIXME: The following keyword arguments are currently recognized:
Georg Brandl116aa622007-08-15 14:28:22 +000073
Georg Brandl116aa622007-08-15 14:28:22 +000074
75.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
76
77 The :func:`Tcl` function is a factory function which creates an object much like
78 that created by the :class:`Tk` class, except that it does not initialize the Tk
79 subsystem. This is most often useful when driving the Tcl interpreter in an
80 environment where one doesn't want to create extraneous toplevel windows, or
81 where one cannot (such as Unix/Linux systems without an X server). An object
82 created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
83 subsystem initialized) by calling its :meth:`loadtk` method.
84
Georg Brandl116aa622007-08-15 14:28:22 +000085
86Other modules that provide Tk support include:
87
Georg Brandlac6060c2008-05-17 18:44:45 +000088:mod:`tkinter.scrolledtext`
Georg Brandl116aa622007-08-15 14:28:22 +000089 Text widget with a vertical scroll bar built in.
90
Georg Brandlac6060c2008-05-17 18:44:45 +000091:mod:`tkinter.colorchooser`
Georg Brandl116aa622007-08-15 14:28:22 +000092 Dialog to let the user choose a color.
93
Georg Brandlac6060c2008-05-17 18:44:45 +000094:mod:`tkinter.commondialog`
Georg Brandl116aa622007-08-15 14:28:22 +000095 Base class for the dialogs defined in the other modules listed here.
96
Georg Brandlac6060c2008-05-17 18:44:45 +000097:mod:`tkinter.filedialog`
Georg Brandl116aa622007-08-15 14:28:22 +000098 Common dialogs to allow the user to specify a file to open or save.
99
Georg Brandlac6060c2008-05-17 18:44:45 +0000100:mod:`tkinter.font`
Georg Brandl116aa622007-08-15 14:28:22 +0000101 Utilities to help work with fonts.
102
Georg Brandlac6060c2008-05-17 18:44:45 +0000103:mod:`tkinter.messagebox`
Georg Brandl116aa622007-08-15 14:28:22 +0000104 Access to standard Tk dialog boxes.
105
Georg Brandlac6060c2008-05-17 18:44:45 +0000106:mod:`tkinter.simpledialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000107 Basic dialogs and convenience functions.
108
Georg Brandlac6060c2008-05-17 18:44:45 +0000109:mod:`tkinter.dnd`
Georg Brandl48310cd2009-01-03 21:18:54 +0000110 Drag-and-drop support for :mod:`tkinter`. This is experimental and should
Georg Brandlac6060c2008-05-17 18:44:45 +0000111 become deprecated when it is replaced with the Tk DND.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
Georg Brandl23d11d32008-09-21 07:50:52 +0000113:mod:`turtle`
Georg Brandl116aa622007-08-15 14:28:22 +0000114 Turtle graphics in a Tk window.
115
116
117Tkinter Life Preserver
118----------------------
119
120.. sectionauthor:: Matt Conway
121
122
123This section is not designed to be an exhaustive tutorial on either Tk or
124Tkinter. Rather, it is intended as a stop gap, providing some introductory
125orientation on the system.
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127Credits:
128
Georg Brandl116aa622007-08-15 14:28:22 +0000129* Tk was written by John Ousterhout while at Berkeley.
130
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000131* Tkinter was written by Steen Lumholt and Guido van Rossum.
132
Georg Brandl116aa622007-08-15 14:28:22 +0000133* This Life Preserver was written by Matt Conway at the University of Virginia.
134
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000135* The HTML rendering, and some liberal editing, was produced from a FrameMaker
Georg Brandl116aa622007-08-15 14:28:22 +0000136 version by Ken Manheimer.
137
138* Fredrik Lundh elaborated and revised the class interface descriptions, to get
139 them current with Tk 4.2.
140
141* Mike Clarkson converted the documentation to LaTeX, and compiled the User
142 Interface chapter of the reference manual.
143
144
145How To Use This Section
146^^^^^^^^^^^^^^^^^^^^^^^
147
148This section is designed in two parts: the first half (roughly) covers
149background material, while the second half can be taken to the keyboard as a
150handy reference.
151
152When trying to answer questions of the form "how do I do blah", it is often best
153to find out how to do"blah" in straight Tk, and then convert this back into the
Georg Brandlac6060c2008-05-17 18:44:45 +0000154corresponding :mod:`tkinter` call. Python programmers can often guess at the
Georg Brandl116aa622007-08-15 14:28:22 +0000155correct Python command by looking at the Tk documentation. This means that in
156order to use Tkinter, you will have to know a little bit about Tk. This document
157can't fulfill that role, so the best we can do is point you to the best
158documentation that exists. Here are some hints:
159
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000160* The authors strongly suggest getting a copy of the Tk man pages.
161 Specifically, the man pages in the ``manN`` directory are most useful.
162 The ``man3`` man pages describe the C interface to the Tk library and thus
163 are not especially helpful for script writers.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
166 Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
167 the novice. The book is not exhaustive, and for many details it defers to the
168 man pages.
169
Georg Brandl48310cd2009-01-03 21:18:54 +0000170* :file:`tkinter/__init__.py` is a last resort for most, but can be a good
Georg Brandlac6060c2008-05-17 18:44:45 +0000171 place to go when nothing else makes sense.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173
174.. seealso::
175
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000176 `Tcl/Tk 8.6 man pages <http://www.tcl.tk/man/tcl8.6/>`_
177 The Tcl/Tk manual on www.tcl.tk.
178
Georg Brandl116aa622007-08-15 14:28:22 +0000179 `ActiveState Tcl Home Page <http://tcl.activestate.com/>`_
180 The Tk/Tcl development is largely taking place at ActiveState.
181
182 `Tcl and the Tk Toolkit <http://www.amazon.com/exec/obidos/ASIN/020163337X>`_
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +0200183 The book by John Ousterhout, the inventor of Tcl.
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185 `Practical Programming in Tcl and Tk <http://www.amazon.com/exec/obidos/ASIN/0130220280>`_
186 Brent Welch's encyclopedic book.
187
188
189A Simple Hello World Program
190^^^^^^^^^^^^^^^^^^^^^^^^^^^^
191
Georg Brandl116aa622007-08-15 14:28:22 +0000192::
193
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700194 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000195
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700196 class Application(tk.Frame):
197 def __init__(self, master=None):
198 tk.Frame.__init__(self, master)
199 self.pack()
200 self.createWidgets()
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700202 def createWidgets(self):
203 self.hi_there = tk.Button(self)
204 self.hi_there["text"] = "Hello World\n(click me)"
205 self.hi_there["command"] = self.say_hi
206 self.hi_there.pack(side="top")
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Andrew Svetlov1d561792012-03-25 11:44:59 +0300208 self.QUIT = tk.Button(self, text="QUIT", fg="red",
209 command=root.destroy)
210 self.QUIT.pack(side="bottom")
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700212 def say_hi(self):
213 print("hi there, everyone!")
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700215 root = tk.Tk()
216 app = Application(master=root)
217 app.mainloop()
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219
220A (Very) Quick Look at Tcl/Tk
221-----------------------------
222
223The class hierarchy looks complicated, but in actual practice, application
224programmers almost always refer to the classes at the very bottom of the
225hierarchy.
226
Georg Brandl116aa622007-08-15 14:28:22 +0000227Notes:
228
229* These classes are provided for the purposes of organizing certain functions
230 under one namespace. They aren't meant to be instantiated independently.
231
232* The :class:`Tk` class is meant to be instantiated only once in an application.
233 Application programmers need not instantiate one explicitly, the system creates
234 one whenever any of the other classes are instantiated.
235
236* The :class:`Widget` class is not meant to be instantiated, it is meant only
237 for subclassing to make "real" widgets (in C++, this is called an 'abstract
238 class').
239
240To make use of this reference material, there will be times when you will need
241to know how to read short passages of Tk and how to identify the various parts
242of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
Georg Brandlac6060c2008-05-17 18:44:45 +0000243:mod:`tkinter` equivalents of what's below.)
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
246of tokens separated by spaces. A Tk widget is just its *class*, the *options*
247that help configure it, and the *actions* that make it do useful things.
248
249To make a widget in Tk, the command is always of the form::
250
251 classCommand newPathname options
252
253*classCommand*
254 denotes which kind of widget to make (a button, a label, a menu...)
255
256*newPathname*
257 is the new name for this widget. All names in Tk must be unique. To help
258 enforce this, widgets in Tk are named with *pathnames*, just like files in a
259 file system. The top level widget, the *root*, is called ``.`` (period) and
260 children are delimited by more periods. For example,
261 ``.myApp.controlPanel.okButton`` might be the name of a widget.
262
263*options*
264 configure the widget's appearance and in some cases, its behavior. The options
265 come in the form of a list of flags and values. Flags are preceded by a '-',
266 like Unix shell command flags, and values are put in quotes if they are more
267 than one word.
268
269For example::
270
271 button .fred -fg red -text "hi there"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000272 ^ ^ \______________________/
Georg Brandl116aa622007-08-15 14:28:22 +0000273 | | |
274 class new options
275 command widget (-opt val -opt val ...)
276
277Once created, the pathname to the widget becomes a new command. This new
278*widget command* is the programmer's handle for getting the new widget to
279perform some *action*. In C, you'd express this as someAction(fred,
280someOptions), in C++, you would express this as fred.someAction(someOptions),
281and in Tk, you say::
282
Georg Brandl48310cd2009-01-03 21:18:54 +0000283 .fred someAction someOptions
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285Note that the object name, ``.fred``, starts with a dot.
286
287As you'd expect, the legal values for *someAction* will depend on the widget's
288class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
289does not work if fred is a label (disabling of labels is not supported in Tk).
290
291The legal values of *someOptions* is action dependent. Some actions, like
292``disable``, require no arguments, others, like a text-entry box's ``delete``
293command, would need arguments to specify what range of text to delete.
294
295
296.. _tkinter-basic-mapping:
297
298Mapping Basic Tk into Tkinter
299-----------------------------
300
301Class commands in Tk correspond to class constructors in Tkinter. ::
302
303 button .fred =====> fred = Button()
304
305The master of an object is implicit in the new name given to it at creation
306time. In Tkinter, masters are specified explicitly. ::
307
308 button .panel.fred =====> fred = Button(panel)
309
310The configuration options in Tk are given in lists of hyphened tags followed by
311values. In Tkinter, options are specified as keyword-arguments in the instance
312constructor, and keyword-args for configure calls or as instance indices, in
313dictionary style, for established instances. See section
314:ref:`tkinter-setting-options` on setting options. ::
315
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000316 button .fred -fg red =====> fred = Button(panel, fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000317 .fred configure -fg red =====> fred["fg"] = red
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000318 OR ==> fred.config(fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320In Tk, to perform an action on a widget, use the widget name as a command, and
321follow it with an action name, possibly with arguments (options). In Tkinter,
322you call methods on the class instance to invoke actions on the widget. The
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000323actions (methods) that a given widget can perform are listed in
324:file:`tkinter/__init__.py`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000325
326 .fred invoke =====> fred.invoke()
327
328To give a widget to the packer (geometry manager), you call pack with optional
329arguments. In Tkinter, the Pack class holds all this functionality, and the
330various forms of the pack command are implemented as methods. All widgets in
Georg Brandlac6060c2008-05-17 18:44:45 +0000331:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
Georg Brandl48310cd2009-01-03 21:18:54 +0000332methods. See the :mod:`tkinter.tix` module documentation for additional
Georg Brandlac6060c2008-05-17 18:44:45 +0000333information on the Form geometry manager. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000334
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000335 pack .fred -side left =====> fred.pack(side="left")
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337
338How Tk and Tkinter are Related
339------------------------------
340
Georg Brandl116aa622007-08-15 14:28:22 +0000341From the top down:
342
343Your App Here (Python)
Georg Brandlac6060c2008-05-17 18:44:45 +0000344 A Python application makes a :mod:`tkinter` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000345
Georg Brandlac6060c2008-05-17 18:44:45 +0000346tkinter (Python Package)
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000347 This call (say, for example, creating a button widget), is implemented in
348 the :mod:`tkinter` package, which is written in Python. This Python
349 function will parse the commands and the arguments and convert them into a
350 form that makes them look as if they had come from a Tk script instead of
351 a Python script.
Georg Brandl116aa622007-08-15 14:28:22 +0000352
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000353_tkinter (C)
Georg Brandl116aa622007-08-15 14:28:22 +0000354 These commands and their arguments will be passed to a C function in the
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000355 :mod:`_tkinter` - note the underscore - extension module.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
357Tk Widgets (C and Tcl)
358 This C function is able to make calls into other C modules, including the C
359 functions that make up the Tk library. Tk is implemented in C and some Tcl.
360 The Tcl part of the Tk widgets is used to bind certain default behaviors to
Georg Brandlac6060c2008-05-17 18:44:45 +0000361 widgets, and is executed once at the point where the Python :mod:`tkinter`
362 package is imported. (The user never sees this stage).
Georg Brandl116aa622007-08-15 14:28:22 +0000363
364Tk (C)
365 The Tk part of the Tk Widgets implement the final mapping to ...
366
367Xlib (C)
368 the Xlib library to draw graphics on the screen.
369
370
371Handy Reference
372---------------
373
374
375.. _tkinter-setting-options:
376
377Setting Options
378^^^^^^^^^^^^^^^
379
380Options control things like the color and border width of a widget. Options can
381be set in three ways:
382
383At object creation time, using keyword arguments
384 ::
385
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000386 fred = Button(self, fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388After object creation, treating the option name like a dictionary index
389 ::
390
391 fred["fg"] = "red"
392 fred["bg"] = "blue"
393
394Use the config() method to update multiple attrs subsequent to object creation
395 ::
396
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000397 fred.config(fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399For a complete explanation of a given option and its behavior, see the Tk man
400pages for the widget in question.
401
402Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
403for each widget. The former is a list of options that are common to many
404widgets, the latter are the options that are idiosyncratic to that particular
405widget. The Standard Options are documented on the :manpage:`options(3)` man
406page.
407
408No distinction between standard and widget-specific options is made in this
409document. Some options don't apply to some kinds of widgets. Whether a given
410widget responds to a particular option depends on the class of the widget;
411buttons have a ``command`` option, labels do not.
412
413The options supported by a given widget are listed in that widget's man page, or
414can be queried at runtime by calling the :meth:`config` method without
415arguments, or by calling the :meth:`keys` method on that widget. The return
416value of these calls is a dictionary whose key is the name of the option as a
417string (for example, ``'relief'``) and whose values are 5-tuples.
418
419Some options, like ``bg`` are synonyms for common options with long names
420(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
421of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
422back will contain the name of the synonym and the "real" option (such as
423``('bg', 'background')``).
424
425+-------+---------------------------------+--------------+
426| Index | Meaning | Example |
427+=======+=================================+==============+
428| 0 | option name | ``'relief'`` |
429+-------+---------------------------------+--------------+
430| 1 | option name for database lookup | ``'relief'`` |
431+-------+---------------------------------+--------------+
432| 2 | option class for database | ``'Relief'`` |
433| | lookup | |
434+-------+---------------------------------+--------------+
435| 3 | default value | ``'raised'`` |
436+-------+---------------------------------+--------------+
437| 4 | current value | ``'groove'`` |
438+-------+---------------------------------+--------------+
439
440Example::
441
Collin Winterc79461b2007-09-01 23:34:30 +0000442 >>> print(fred.config())
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200443 {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445Of course, the dictionary printed will include all the options available and
446their values. This is meant only as an example.
447
448
449The Packer
450^^^^^^^^^^
451
452.. index:: single: packing (widgets)
453
Georg Brandl116aa622007-08-15 14:28:22 +0000454The packer is one of Tk's geometry-management mechanisms. Geometry managers
455are used to specify the relative positioning of the positioning of widgets
456within their container - their mutual *master*. In contrast to the more
457cumbersome *placer* (which is used less commonly, and we do not cover here), the
458packer takes qualitative relationship specification - *above*, *to the left of*,
459*filling*, etc - and works everything out to determine the exact placement
460coordinates for you.
461
Georg Brandl116aa622007-08-15 14:28:22 +0000462The size of any *master* widget is determined by the size of the "slave widgets"
463inside. The packer is used to control where slave widgets appear inside the
464master into which they are packed. You can pack widgets into frames, and frames
465into other frames, in order to achieve the kind of layout you desire.
466Additionally, the arrangement is dynamically adjusted to accommodate incremental
467changes to the configuration, once it is packed.
468
469Note that widgets do not appear until they have had their geometry specified
470with a geometry manager. It's a common early mistake to leave out the geometry
471specification, and then be surprised when the widget is created but nothing
472appears. A widget will appear only after it has had, for example, the packer's
473:meth:`pack` method applied to it.
474
475The pack() method can be called with keyword-option/value pairs that control
476where the widget is to appear within its container, and how it is to behave when
477the main application window is resized. Here are some examples::
478
479 fred.pack() # defaults to side = "top"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000480 fred.pack(side="left")
481 fred.pack(expand=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483
484Packer Options
485^^^^^^^^^^^^^^
486
487For more extensive information on the packer and the options that it can take,
488see the man pages and page 183 of John Ousterhout's book.
489
Georg Brandl48310cd2009-01-03 21:18:54 +0000490anchor
Georg Brandl116aa622007-08-15 14:28:22 +0000491 Anchor type. Denotes where the packer is to place each slave in its parcel.
492
493expand
494 Boolean, ``0`` or ``1``.
495
496fill
497 Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
498
499ipadx and ipady
500 A distance - designating internal padding on each side of the slave widget.
501
502padx and pady
503 A distance - designating external padding on each side of the slave widget.
504
505side
506 Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
507
508
509Coupling Widget Variables
510^^^^^^^^^^^^^^^^^^^^^^^^^
511
512The current-value setting of some widgets (like text entry widgets) can be
513connected directly to application variables by using special options. These
514options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
515``value``. This connection works both ways: if the variable changes for any
516reason, the widget it's connected to will be updated to reflect the new value.
517
Georg Brandlac6060c2008-05-17 18:44:45 +0000518Unfortunately, in the current implementation of :mod:`tkinter` it is not
Georg Brandl116aa622007-08-15 14:28:22 +0000519possible to hand over an arbitrary Python variable to a widget through a
520``variable`` or ``textvariable`` option. The only kinds of variables for which
521this works are variables that are subclassed from a class called Variable,
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000522defined in :mod:`tkinter`.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524There are many useful subclasses of Variable already defined:
525:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
526:class:`BooleanVar`. To read the current value of such a variable, call the
Georg Brandl502d9a52009-07-26 15:02:41 +0000527:meth:`get` method on it, and to change its value you call the :meth:`!set`
Georg Brandl116aa622007-08-15 14:28:22 +0000528method. If you follow this protocol, the widget will always track the value of
529the variable, with no further intervention on your part.
530
531For example::
532
533 class App(Frame):
534 def __init__(self, master=None):
535 Frame.__init__(self, master)
536 self.pack()
537
538 self.entrythingy = Entry()
539 self.entrythingy.pack()
540
541 # here is the application variable
542 self.contents = StringVar()
543 # set it to some value
544 self.contents.set("this is a variable")
545 # tell the entry widget to watch this variable
546 self.entrythingy["textvariable"] = self.contents
547
548 # and here we get a callback when the user hits return.
549 # we will have the program print out the value of the
550 # application variable when the user hits return
551 self.entrythingy.bind('<Key-Return>',
552 self.print_contents)
553
554 def print_contents(self, event):
Collin Winterc79461b2007-09-01 23:34:30 +0000555 print("hi. contents of entry is now ---->",
556 self.contents.get())
Georg Brandl116aa622007-08-15 14:28:22 +0000557
558
559The Window Manager
560^^^^^^^^^^^^^^^^^^
561
562.. index:: single: window manager (widgets)
563
Georg Brandl116aa622007-08-15 14:28:22 +0000564In Tk, there is a utility command, ``wm``, for interacting with the window
565manager. Options to the ``wm`` command allow you to control things like titles,
Georg Brandlac6060c2008-05-17 18:44:45 +0000566placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
Georg Brandl116aa622007-08-15 14:28:22 +0000567been implemented as methods on the :class:`Wm` class. Toplevel widgets are
568subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
569directly.
570
571To get at the toplevel window that contains a given widget, you can often just
572refer to the widget's master. Of course if the widget has been packed inside of
573a frame, the master won't represent a toplevel window. To get at the toplevel
574window that contains an arbitrary widget, you can call the :meth:`_root` method.
575This method begins with an underscore to denote the fact that this function is
576part of the implementation, and not an interface to Tk functionality.
577
Georg Brandl116aa622007-08-15 14:28:22 +0000578Here are some examples of typical usage::
579
Georg Brandlac6060c2008-05-17 18:44:45 +0000580 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +0000581 class App(Frame):
582 def __init__(self, master=None):
583 Frame.__init__(self, master)
584 self.pack()
585
586
587 # create the application
588 myapp = App()
589
590 #
591 # here are method calls to the window manager class
592 #
593 myapp.master.title("My Do-Nothing Application")
594 myapp.master.maxsize(1000, 400)
595
596 # start the program
597 myapp.mainloop()
598
599
600Tk Option Data Types
601^^^^^^^^^^^^^^^^^^^^
602
603.. index:: single: Tk Option Data Types
604
Georg Brandl116aa622007-08-15 14:28:22 +0000605anchor
606 Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
607 ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
608
609bitmap
610 There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
611 ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
612 ``'warning'``. To specify an X bitmap filename, give the full path to the file,
613 preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
614
615boolean
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +0200616 You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000617
618callback
619 This is any Python function that takes no arguments. For example::
620
621 def print_it():
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000622 print("hi there")
Georg Brandl116aa622007-08-15 14:28:22 +0000623 fred["command"] = print_it
624
625color
626 Colors can be given as the names of X colors in the rgb.txt file, or as strings
627 representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
628 ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
629 represent any legal hex digit. See page 160 of Ousterhout's book for details.
630
631cursor
632 The standard X cursor names from :file:`cursorfont.h` can be used, without the
633 ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
634 string ``"hand2"``. You can also specify a bitmap and mask file of your own.
635 See page 179 of Ousterhout's book.
636
637distance
638 Screen distances can be specified in either pixels or absolute distances.
639 Pixels are given as numbers and absolute distances as strings, with the trailing
640 character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
641 millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
642 as ``"3.5i"``.
643
644font
645 Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
646 positive numbers are measured in points; sizes with negative numbers are
647 measured in pixels.
648
649geometry
650 This is a string of the form ``widthxheight``, where width and height are
651 measured in pixels for most widgets (in characters for widgets displaying text).
652 For example: ``fred["geometry"] = "200x100"``.
653
654justify
655 Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
656 ``"fill"``.
657
658region
659 This is a string with four space-delimited elements, each of which is a legal
660 distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
661 ``"3c 2c 4c 10.43c"`` are all legal regions.
662
663relief
664 Determines what the border style of a widget will be. Legal values are:
665 ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
666
667scrollcommand
Georg Brandl502d9a52009-07-26 15:02:41 +0000668 This is almost always the :meth:`!set` method of some scrollbar widget, but can
Georg Brandl59b44722010-12-30 22:12:40 +0000669 be any widget method that takes a single argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671wrap:
672 Must be one of: ``"none"``, ``"char"``, or ``"word"``.
673
674
675Bindings and Events
676^^^^^^^^^^^^^^^^^^^
677
678.. index::
679 single: bind (widgets)
680 single: events (widgets)
681
Georg Brandl116aa622007-08-15 14:28:22 +0000682The bind method from the widget command allows you to watch for certain events
683and to have a callback function trigger when that event type occurs. The form
684of the bind method is::
685
686 def bind(self, sequence, func, add=''):
687
688where:
689
690sequence
691 is a string that denotes the target kind of event. (See the bind man page and
692 page 201 of John Ousterhout's book for details).
693
694func
695 is a Python function, taking one argument, to be invoked when the event occurs.
696 An Event instance will be passed as the argument. (Functions deployed this way
697 are commonly known as *callbacks*.)
698
699add
700 is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
701 this binding is to replace any other bindings that this event is associated
702 with. Passing a ``'+'`` means that this function is to be added to the list
703 of functions bound to this event type.
704
705For example::
706
707 def turnRed(self, event):
708 event.widget["activeforeground"] = "red"
709
710 self.button.bind("<Enter>", self.turnRed)
711
712Notice how the widget field of the event is being accessed in the
713:meth:`turnRed` callback. This field contains the widget that caught the X
714event. The following table lists the other event fields you can access, and how
715they are denoted in Tk, which can be useful when referring to the Tk man pages.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000717+----+---------------------+----+---------------------+
718| Tk | Tkinter Event Field | Tk | Tkinter Event Field |
719+====+=====================+====+=====================+
720| %f | focus | %A | char |
721+----+---------------------+----+---------------------+
722| %h | height | %E | send_event |
723+----+---------------------+----+---------------------+
724| %k | keycode | %K | keysym |
725+----+---------------------+----+---------------------+
726| %s | state | %N | keysym_num |
727+----+---------------------+----+---------------------+
728| %t | time | %T | type |
729+----+---------------------+----+---------------------+
730| %w | width | %W | widget |
731+----+---------------------+----+---------------------+
732| %x | x | %X | x_root |
733+----+---------------------+----+---------------------+
734| %y | y | %Y | y_root |
735+----+---------------------+----+---------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000736
737
738The index Parameter
739^^^^^^^^^^^^^^^^^^^
740
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000741A number of widgets require "index" parameters to be passed. These are used to
Georg Brandl116aa622007-08-15 14:28:22 +0000742point at a specific place in a Text widget, or to particular characters in an
743Entry widget, or to particular menu items in a Menu widget.
744
Georg Brandl116aa622007-08-15 14:28:22 +0000745Entry widget indexes (index, view index, etc.)
746 Entry widgets have options that refer to character positions in the text being
Georg Brandlac6060c2008-05-17 18:44:45 +0000747 displayed. You can use these :mod:`tkinter` functions to access these special
Georg Brandl116aa622007-08-15 14:28:22 +0000748 points in text widgets:
749
Georg Brandl116aa622007-08-15 14:28:22 +0000750Text widget indexes
751 The index notation for Text widgets is very rich and is best described in the Tk
752 man pages.
753
754Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
755 Some options and methods for menus manipulate specific menu entries. Anytime a
756 menu index is needed for an option or a parameter, you may pass in:
757
758 * an integer which refers to the numeric position of the entry in the widget,
759 counted from the top, starting with 0;
760
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000761 * the string ``"active"``, which refers to the menu position that is currently
Georg Brandl116aa622007-08-15 14:28:22 +0000762 under the cursor;
763
764 * the string ``"last"`` which refers to the last menu item;
765
766 * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
767 as a y pixel coordinate in the menu's coordinate system;
768
769 * the string ``"none"``, which indicates no menu entry at all, most often used
770 with menu.activate() to deactivate all entries, and finally,
771
772 * a text string that is pattern matched against the label of the menu entry, as
773 scanned from the top of the menu to the bottom. Note that this index type is
774 considered after all the others, which means that matches for menu items
775 labelled ``last``, ``active``, or ``none`` may be interpreted as the above
776 literals, instead.
777
778
779Images
780^^^^^^
781
782Bitmap/Pixelmap images can be created through the subclasses of
Georg Brandlac6060c2008-05-17 18:44:45 +0000783:class:`tkinter.Image`:
Georg Brandl116aa622007-08-15 14:28:22 +0000784
785* :class:`BitmapImage` can be used for X11 bitmap data.
786
787* :class:`PhotoImage` can be used for GIF and PPM/PGM color bitmaps.
788
789Either type of image is created through either the ``file`` or the ``data``
790option (other options are available as well).
791
792The image object can then be used wherever an ``image`` option is supported by
793some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
794reference to the image. When the last Python reference to the image object is
795deleted, the image data is deleted as well, and Tk will display an empty box
796wherever the image was used.