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