blob: f6e095a5c040bc6377019a9fd613dfff9cbdc9bf [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
Georg Brandlac6060c2008-05-17 18:44:45 +0000197 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199 class Application(Frame):
200 def say_hi(self):
Collin Winterc79461b2007-09-01 23:34:30 +0000201 print("hi there, everyone!")
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203 def createWidgets(self):
204 self.QUIT = Button(self)
205 self.QUIT["text"] = "QUIT"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000206 self.QUIT["fg"] = "red"
207 self.QUIT["command"] = self.quit
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209 self.QUIT.pack({"side": "left"})
210
211 self.hi_there = Button(self)
212 self.hi_there["text"] = "Hello",
213 self.hi_there["command"] = self.say_hi
214
215 self.hi_there.pack({"side": "left"})
216
217 def __init__(self, master=None):
218 Frame.__init__(self, master)
219 self.pack()
220 self.createWidgets()
221
222 root = Tk()
223 app = Application(master=root)
224 app.mainloop()
225 root.destroy()
226
227
228A (Very) Quick Look at Tcl/Tk
229-----------------------------
230
231The class hierarchy looks complicated, but in actual practice, application
232programmers almost always refer to the classes at the very bottom of the
233hierarchy.
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235Notes:
236
237* These classes are provided for the purposes of organizing certain functions
238 under one namespace. They aren't meant to be instantiated independently.
239
240* The :class:`Tk` class is meant to be instantiated only once in an application.
241 Application programmers need not instantiate one explicitly, the system creates
242 one whenever any of the other classes are instantiated.
243
244* The :class:`Widget` class is not meant to be instantiated, it is meant only
245 for subclassing to make "real" widgets (in C++, this is called an 'abstract
246 class').
247
248To make use of this reference material, there will be times when you will need
249to know how to read short passages of Tk and how to identify the various parts
250of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
Georg Brandlac6060c2008-05-17 18:44:45 +0000251:mod:`tkinter` equivalents of what's below.)
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
254of tokens separated by spaces. A Tk widget is just its *class*, the *options*
255that help configure it, and the *actions* that make it do useful things.
256
257To make a widget in Tk, the command is always of the form::
258
259 classCommand newPathname options
260
261*classCommand*
262 denotes which kind of widget to make (a button, a label, a menu...)
263
264*newPathname*
265 is the new name for this widget. All names in Tk must be unique. To help
266 enforce this, widgets in Tk are named with *pathnames*, just like files in a
267 file system. The top level widget, the *root*, is called ``.`` (period) and
268 children are delimited by more periods. For example,
269 ``.myApp.controlPanel.okButton`` might be the name of a widget.
270
271*options*
272 configure the widget's appearance and in some cases, its behavior. The options
273 come in the form of a list of flags and values. Flags are preceded by a '-',
274 like Unix shell command flags, and values are put in quotes if they are more
275 than one word.
276
277For example::
278
279 button .fred -fg red -text "hi there"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000280 ^ ^ \______________________/
Georg Brandl116aa622007-08-15 14:28:22 +0000281 | | |
282 class new options
283 command widget (-opt val -opt val ...)
284
285Once created, the pathname to the widget becomes a new command. This new
286*widget command* is the programmer's handle for getting the new widget to
287perform some *action*. In C, you'd express this as someAction(fred,
288someOptions), in C++, you would express this as fred.someAction(someOptions),
289and in Tk, you say::
290
Georg Brandl48310cd2009-01-03 21:18:54 +0000291 .fred someAction someOptions
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293Note that the object name, ``.fred``, starts with a dot.
294
295As you'd expect, the legal values for *someAction* will depend on the widget's
296class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
297does not work if fred is a label (disabling of labels is not supported in Tk).
298
299The legal values of *someOptions* is action dependent. Some actions, like
300``disable``, require no arguments, others, like a text-entry box's ``delete``
301command, would need arguments to specify what range of text to delete.
302
303
304.. _tkinter-basic-mapping:
305
306Mapping Basic Tk into Tkinter
307-----------------------------
308
309Class commands in Tk correspond to class constructors in Tkinter. ::
310
311 button .fred =====> fred = Button()
312
313The master of an object is implicit in the new name given to it at creation
314time. In Tkinter, masters are specified explicitly. ::
315
316 button .panel.fred =====> fred = Button(panel)
317
318The configuration options in Tk are given in lists of hyphened tags followed by
319values. In Tkinter, options are specified as keyword-arguments in the instance
320constructor, and keyword-args for configure calls or as instance indices, in
321dictionary style, for established instances. See section
322:ref:`tkinter-setting-options` on setting options. ::
323
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000324 button .fred -fg red =====> fred = Button(panel, fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000325 .fred configure -fg red =====> fred["fg"] = red
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000326 OR ==> fred.config(fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328In Tk, to perform an action on a widget, use the widget name as a command, and
329follow it with an action name, possibly with arguments (options). In Tkinter,
330you call methods on the class instance to invoke actions on the widget. The
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000331actions (methods) that a given widget can perform are listed in
332:file:`tkinter/__init__.py`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334 .fred invoke =====> fred.invoke()
335
336To give a widget to the packer (geometry manager), you call pack with optional
337arguments. In Tkinter, the Pack class holds all this functionality, and the
338various forms of the pack command are implemented as methods. All widgets in
Georg Brandlac6060c2008-05-17 18:44:45 +0000339:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
Georg Brandl48310cd2009-01-03 21:18:54 +0000340methods. See the :mod:`tkinter.tix` module documentation for additional
Georg Brandlac6060c2008-05-17 18:44:45 +0000341information on the Form geometry manager. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000342
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000343 pack .fred -side left =====> fred.pack(side="left")
Georg Brandl116aa622007-08-15 14:28:22 +0000344
345
346How Tk and Tkinter are Related
347------------------------------
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349From the top down:
350
351Your App Here (Python)
Georg Brandlac6060c2008-05-17 18:44:45 +0000352 A Python application makes a :mod:`tkinter` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
Georg Brandlac6060c2008-05-17 18:44:45 +0000354tkinter (Python Package)
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000355 This call (say, for example, creating a button widget), is implemented in
356 the :mod:`tkinter` package, which is written in Python. This Python
357 function will parse the commands and the arguments and convert them into a
358 form that makes them look as if they had come from a Tk script instead of
359 a Python script.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000361_tkinter (C)
Georg Brandl116aa622007-08-15 14:28:22 +0000362 These commands and their arguments will be passed to a C function in the
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000363 :mod:`_tkinter` - note the underscore - extension module.
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365Tk Widgets (C and Tcl)
366 This C function is able to make calls into other C modules, including the C
367 functions that make up the Tk library. Tk is implemented in C and some Tcl.
368 The Tcl part of the Tk widgets is used to bind certain default behaviors to
Georg Brandlac6060c2008-05-17 18:44:45 +0000369 widgets, and is executed once at the point where the Python :mod:`tkinter`
370 package is imported. (The user never sees this stage).
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372Tk (C)
373 The Tk part of the Tk Widgets implement the final mapping to ...
374
375Xlib (C)
376 the Xlib library to draw graphics on the screen.
377
378
379Handy Reference
380---------------
381
382
383.. _tkinter-setting-options:
384
385Setting Options
386^^^^^^^^^^^^^^^
387
388Options control things like the color and border width of a widget. Options can
389be set in three ways:
390
391At object creation time, using keyword arguments
392 ::
393
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000394 fred = Button(self, fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396After object creation, treating the option name like a dictionary index
397 ::
398
399 fred["fg"] = "red"
400 fred["bg"] = "blue"
401
402Use the config() method to update multiple attrs subsequent to object creation
403 ::
404
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000405 fred.config(fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407For a complete explanation of a given option and its behavior, see the Tk man
408pages for the widget in question.
409
410Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
411for each widget. The former is a list of options that are common to many
412widgets, the latter are the options that are idiosyncratic to that particular
413widget. The Standard Options are documented on the :manpage:`options(3)` man
414page.
415
416No distinction between standard and widget-specific options is made in this
417document. Some options don't apply to some kinds of widgets. Whether a given
418widget responds to a particular option depends on the class of the widget;
419buttons have a ``command`` option, labels do not.
420
421The options supported by a given widget are listed in that widget's man page, or
422can be queried at runtime by calling the :meth:`config` method without
423arguments, or by calling the :meth:`keys` method on that widget. The return
424value of these calls is a dictionary whose key is the name of the option as a
425string (for example, ``'relief'``) and whose values are 5-tuples.
426
427Some options, like ``bg`` are synonyms for common options with long names
428(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
429of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
430back will contain the name of the synonym and the "real" option (such as
431``('bg', 'background')``).
432
433+-------+---------------------------------+--------------+
434| Index | Meaning | Example |
435+=======+=================================+==============+
436| 0 | option name | ``'relief'`` |
437+-------+---------------------------------+--------------+
438| 1 | option name for database lookup | ``'relief'`` |
439+-------+---------------------------------+--------------+
440| 2 | option class for database | ``'Relief'`` |
441| | lookup | |
442+-------+---------------------------------+--------------+
443| 3 | default value | ``'raised'`` |
444+-------+---------------------------------+--------------+
445| 4 | current value | ``'groove'`` |
446+-------+---------------------------------+--------------+
447
448Example::
449
Collin Winterc79461b2007-09-01 23:34:30 +0000450 >>> print(fred.config())
Georg Brandl116aa622007-08-15 14:28:22 +0000451 {'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
452
453Of course, the dictionary printed will include all the options available and
454their values. This is meant only as an example.
455
456
457The Packer
458^^^^^^^^^^
459
460.. index:: single: packing (widgets)
461
Georg Brandl116aa622007-08-15 14:28:22 +0000462The packer is one of Tk's geometry-management mechanisms. Geometry managers
463are used to specify the relative positioning of the positioning of widgets
464within their container - their mutual *master*. In contrast to the more
465cumbersome *placer* (which is used less commonly, and we do not cover here), the
466packer takes qualitative relationship specification - *above*, *to the left of*,
467*filling*, etc - and works everything out to determine the exact placement
468coordinates for you.
469
Georg Brandl116aa622007-08-15 14:28:22 +0000470The size of any *master* widget is determined by the size of the "slave widgets"
471inside. The packer is used to control where slave widgets appear inside the
472master into which they are packed. You can pack widgets into frames, and frames
473into other frames, in order to achieve the kind of layout you desire.
474Additionally, the arrangement is dynamically adjusted to accommodate incremental
475changes to the configuration, once it is packed.
476
477Note that widgets do not appear until they have had their geometry specified
478with a geometry manager. It's a common early mistake to leave out the geometry
479specification, and then be surprised when the widget is created but nothing
480appears. A widget will appear only after it has had, for example, the packer's
481:meth:`pack` method applied to it.
482
483The pack() method can be called with keyword-option/value pairs that control
484where the widget is to appear within its container, and how it is to behave when
485the main application window is resized. Here are some examples::
486
487 fred.pack() # defaults to side = "top"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000488 fred.pack(side="left")
489 fred.pack(expand=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000490
491
492Packer Options
493^^^^^^^^^^^^^^
494
495For more extensive information on the packer and the options that it can take,
496see the man pages and page 183 of John Ousterhout's book.
497
Georg Brandl48310cd2009-01-03 21:18:54 +0000498anchor
Georg Brandl116aa622007-08-15 14:28:22 +0000499 Anchor type. Denotes where the packer is to place each slave in its parcel.
500
501expand
502 Boolean, ``0`` or ``1``.
503
504fill
505 Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
506
507ipadx and ipady
508 A distance - designating internal padding on each side of the slave widget.
509
510padx and pady
511 A distance - designating external padding on each side of the slave widget.
512
513side
514 Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
515
516
517Coupling Widget Variables
518^^^^^^^^^^^^^^^^^^^^^^^^^
519
520The current-value setting of some widgets (like text entry widgets) can be
521connected directly to application variables by using special options. These
522options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
523``value``. This connection works both ways: if the variable changes for any
524reason, the widget it's connected to will be updated to reflect the new value.
525
Georg Brandlac6060c2008-05-17 18:44:45 +0000526Unfortunately, in the current implementation of :mod:`tkinter` it is not
Georg Brandl116aa622007-08-15 14:28:22 +0000527possible to hand over an arbitrary Python variable to a widget through a
528``variable`` or ``textvariable`` option. The only kinds of variables for which
529this works are variables that are subclassed from a class called Variable,
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000530defined in :mod:`tkinter`.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532There are many useful subclasses of Variable already defined:
533:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
534:class:`BooleanVar`. To read the current value of such a variable, call the
Georg Brandl502d9a52009-07-26 15:02:41 +0000535:meth:`get` method on it, and to change its value you call the :meth:`!set`
Georg Brandl116aa622007-08-15 14:28:22 +0000536method. If you follow this protocol, the widget will always track the value of
537the variable, with no further intervention on your part.
538
539For example::
540
541 class App(Frame):
542 def __init__(self, master=None):
543 Frame.__init__(self, master)
544 self.pack()
545
546 self.entrythingy = Entry()
547 self.entrythingy.pack()
548
549 # here is the application variable
550 self.contents = StringVar()
551 # set it to some value
552 self.contents.set("this is a variable")
553 # tell the entry widget to watch this variable
554 self.entrythingy["textvariable"] = self.contents
555
556 # and here we get a callback when the user hits return.
557 # we will have the program print out the value of the
558 # application variable when the user hits return
559 self.entrythingy.bind('<Key-Return>',
560 self.print_contents)
561
562 def print_contents(self, event):
Collin Winterc79461b2007-09-01 23:34:30 +0000563 print("hi. contents of entry is now ---->",
564 self.contents.get())
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566
567The Window Manager
568^^^^^^^^^^^^^^^^^^
569
570.. index:: single: window manager (widgets)
571
Georg Brandl116aa622007-08-15 14:28:22 +0000572In Tk, there is a utility command, ``wm``, for interacting with the window
573manager. Options to the ``wm`` command allow you to control things like titles,
Georg Brandlac6060c2008-05-17 18:44:45 +0000574placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
Georg Brandl116aa622007-08-15 14:28:22 +0000575been implemented as methods on the :class:`Wm` class. Toplevel widgets are
576subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
577directly.
578
579To get at the toplevel window that contains a given widget, you can often just
580refer to the widget's master. Of course if the widget has been packed inside of
581a frame, the master won't represent a toplevel window. To get at the toplevel
582window that contains an arbitrary widget, you can call the :meth:`_root` method.
583This method begins with an underscore to denote the fact that this function is
584part of the implementation, and not an interface to Tk functionality.
585
Georg Brandl116aa622007-08-15 14:28:22 +0000586Here are some examples of typical usage::
587
Georg Brandlac6060c2008-05-17 18:44:45 +0000588 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +0000589 class App(Frame):
590 def __init__(self, master=None):
591 Frame.__init__(self, master)
592 self.pack()
593
594
595 # create the application
596 myapp = App()
597
598 #
599 # here are method calls to the window manager class
600 #
601 myapp.master.title("My Do-Nothing Application")
602 myapp.master.maxsize(1000, 400)
603
604 # start the program
605 myapp.mainloop()
606
607
608Tk Option Data Types
609^^^^^^^^^^^^^^^^^^^^
610
611.. index:: single: Tk Option Data Types
612
Georg Brandl116aa622007-08-15 14:28:22 +0000613anchor
614 Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
615 ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
616
617bitmap
618 There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
619 ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
620 ``'warning'``. To specify an X bitmap filename, give the full path to the file,
621 preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
622
623boolean
624 You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"`` .
625
626callback
627 This is any Python function that takes no arguments. For example::
628
629 def print_it():
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000630 print("hi there")
Georg Brandl116aa622007-08-15 14:28:22 +0000631 fred["command"] = print_it
632
633color
634 Colors can be given as the names of X colors in the rgb.txt file, or as strings
635 representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
636 ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
637 represent any legal hex digit. See page 160 of Ousterhout's book for details.
638
639cursor
640 The standard X cursor names from :file:`cursorfont.h` can be used, without the
641 ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
642 string ``"hand2"``. You can also specify a bitmap and mask file of your own.
643 See page 179 of Ousterhout's book.
644
645distance
646 Screen distances can be specified in either pixels or absolute distances.
647 Pixels are given as numbers and absolute distances as strings, with the trailing
648 character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
649 millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
650 as ``"3.5i"``.
651
652font
653 Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
654 positive numbers are measured in points; sizes with negative numbers are
655 measured in pixels.
656
657geometry
658 This is a string of the form ``widthxheight``, where width and height are
659 measured in pixels for most widgets (in characters for widgets displaying text).
660 For example: ``fred["geometry"] = "200x100"``.
661
662justify
663 Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
664 ``"fill"``.
665
666region
667 This is a string with four space-delimited elements, each of which is a legal
668 distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
669 ``"3c 2c 4c 10.43c"`` are all legal regions.
670
671relief
672 Determines what the border style of a widget will be. Legal values are:
673 ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
674
675scrollcommand
Georg Brandl502d9a52009-07-26 15:02:41 +0000676 This is almost always the :meth:`!set` method of some scrollbar widget, but can
Georg Brandl59b44722010-12-30 22:12:40 +0000677 be any widget method that takes a single argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679wrap:
680 Must be one of: ``"none"``, ``"char"``, or ``"word"``.
681
682
683Bindings and Events
684^^^^^^^^^^^^^^^^^^^
685
686.. index::
687 single: bind (widgets)
688 single: events (widgets)
689
Georg Brandl116aa622007-08-15 14:28:22 +0000690The bind method from the widget command allows you to watch for certain events
691and to have a callback function trigger when that event type occurs. The form
692of the bind method is::
693
694 def bind(self, sequence, func, add=''):
695
696where:
697
698sequence
699 is a string that denotes the target kind of event. (See the bind man page and
700 page 201 of John Ousterhout's book for details).
701
702func
703 is a Python function, taking one argument, to be invoked when the event occurs.
704 An Event instance will be passed as the argument. (Functions deployed this way
705 are commonly known as *callbacks*.)
706
707add
708 is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
709 this binding is to replace any other bindings that this event is associated
710 with. Passing a ``'+'`` means that this function is to be added to the list
711 of functions bound to this event type.
712
713For example::
714
715 def turnRed(self, event):
716 event.widget["activeforeground"] = "red"
717
718 self.button.bind("<Enter>", self.turnRed)
719
720Notice how the widget field of the event is being accessed in the
721:meth:`turnRed` callback. This field contains the widget that caught the X
722event. The following table lists the other event fields you can access, and how
723they are denoted in Tk, which can be useful when referring to the Tk man pages.
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000725+----+---------------------+----+---------------------+
726| Tk | Tkinter Event Field | Tk | Tkinter Event Field |
727+====+=====================+====+=====================+
728| %f | focus | %A | char |
729+----+---------------------+----+---------------------+
730| %h | height | %E | send_event |
731+----+---------------------+----+---------------------+
732| %k | keycode | %K | keysym |
733+----+---------------------+----+---------------------+
734| %s | state | %N | keysym_num |
735+----+---------------------+----+---------------------+
736| %t | time | %T | type |
737+----+---------------------+----+---------------------+
738| %w | width | %W | widget |
739+----+---------------------+----+---------------------+
740| %x | x | %X | x_root |
741+----+---------------------+----+---------------------+
742| %y | y | %Y | y_root |
743+----+---------------------+----+---------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745
746The index Parameter
747^^^^^^^^^^^^^^^^^^^
748
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000749A number of widgets require "index" parameters to be passed. These are used to
Georg Brandl116aa622007-08-15 14:28:22 +0000750point at a specific place in a Text widget, or to particular characters in an
751Entry widget, or to particular menu items in a Menu widget.
752
Georg Brandl116aa622007-08-15 14:28:22 +0000753Entry widget indexes (index, view index, etc.)
754 Entry widgets have options that refer to character positions in the text being
Georg Brandlac6060c2008-05-17 18:44:45 +0000755 displayed. You can use these :mod:`tkinter` functions to access these special
Georg Brandl116aa622007-08-15 14:28:22 +0000756 points in text widgets:
757
758 AtEnd()
759 refers to the last position in the text
760
761 AtInsert()
762 refers to the point where the text cursor is
763
764 AtSelFirst()
765 indicates the beginning point of the selected text
766
767 AtSelLast()
768 denotes the last point of the selected text and finally
769
770 At(x[, y])
771 refers to the character at pixel location *x*, *y* (with *y* not used in the
772 case of a text entry widget, which contains a single line of text).
773
774Text widget indexes
775 The index notation for Text widgets is very rich and is best described in the Tk
776 man pages.
777
778Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
779 Some options and methods for menus manipulate specific menu entries. Anytime a
780 menu index is needed for an option or a parameter, you may pass in:
781
782 * an integer which refers to the numeric position of the entry in the widget,
783 counted from the top, starting with 0;
784
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000785 * the string ``"active"``, which refers to the menu position that is currently
Georg Brandl116aa622007-08-15 14:28:22 +0000786 under the cursor;
787
788 * the string ``"last"`` which refers to the last menu item;
789
790 * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
791 as a y pixel coordinate in the menu's coordinate system;
792
793 * the string ``"none"``, which indicates no menu entry at all, most often used
794 with menu.activate() to deactivate all entries, and finally,
795
796 * a text string that is pattern matched against the label of the menu entry, as
797 scanned from the top of the menu to the bottom. Note that this index type is
798 considered after all the others, which means that matches for menu items
799 labelled ``last``, ``active``, or ``none`` may be interpreted as the above
800 literals, instead.
801
802
803Images
804^^^^^^
805
806Bitmap/Pixelmap images can be created through the subclasses of
Georg Brandlac6060c2008-05-17 18:44:45 +0000807:class:`tkinter.Image`:
Georg Brandl116aa622007-08-15 14:28:22 +0000808
809* :class:`BitmapImage` can be used for X11 bitmap data.
810
811* :class:`PhotoImage` can be used for GIF and PPM/PGM color bitmaps.
812
813Either type of image is created through either the ``file`` or the ``data``
814option (other options are available as well).
815
816The image object can then be used wherever an ``image`` option is supported by
817some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
818reference to the image. When the last Python reference to the image object is
819deleted, the image data is deleted as well, and Tk will display an empty box
820wherever the image was used.
821