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