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