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