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