| 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 |
| Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 6 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 7 | .. moduleauthor:: Guido van Rossum <guido@Python.org> |
| 8 | |
| Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 9 | **Source code:** :source:`Lib/tkinter/__init__.py` |
| 10 | |
| 11 | -------------- |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 12 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 13 | The :mod:`tkinter` package ("Tk interface") is the standard Python interface to |
| Miss Islington (bot) | 61ecd3e | 2021-08-22 11:54:46 -0700 | [diff] [blame] | 14 | the Tcl/Tk GUI toolkit. Both Tk and :mod:`tkinter` are available on most Unix |
| 15 | platforms, including macOS, as well as on Windows systems. |
| Andrés Delfino | 67a8f4f | 2018-04-25 14:53:58 -0300 | [diff] [blame] | 16 | |
| 17 | Running ``python -m tkinter`` from the command line should open a window |
| 18 | demonstrating a simple Tk interface, letting you know that :mod:`tkinter` is |
| 19 | properly installed on your system, and also showing what version of Tcl/Tk is |
| 20 | installed, so you can read the Tcl/Tk documentation specific to that version. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 21 | |
| Miss Islington (bot) | 2666d70 | 2021-08-11 10:16:10 -0700 | [diff] [blame] | 22 | Tkinter supports a range of Tcl/Tk versions, built either with or |
| 23 | without thread support. The official Python binary release bundles Tcl/Tk 8.6 |
| 24 | threaded. See the source code for the :mod:`_tkinter` module |
| 25 | for more information about supported versions. |
| 26 | |
| 27 | Tkinter is not a thin wrapper, but adds a fair amount of its own logic to |
| 28 | make the experience more pythonic. This documentation will concentrate on these |
| 29 | additions and changes, and refer to the official Tcl/Tk documentation for |
| 30 | details that are unchanged. |
| 31 | |
| Miss Islington (bot) | 8351df6 | 2021-08-23 12:22:29 -0700 | [diff] [blame] | 32 | .. note:: |
| 33 | |
| 34 | Tcl/Tk 8.5 (2007) introduced a modern set of themed user interface components |
| 35 | along with a new API to use them. Both old and new APIs are still available. |
| 36 | Most documentation you will find online still uses the old API and |
| 37 | can be woefully outdated. |
| 38 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 39 | .. seealso:: |
| 40 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 41 | * `TkDocs <http://tkdocs.com/>`_ |
| 42 | Extensive tutorial on creating user interfaces with Tkinter. Explains key concepts, |
| 43 | and illustrates recommended approaches using the modern API. |
| Andrés Delfino | 67a8f4f | 2018-04-25 14:53:58 -0300 | [diff] [blame] | 44 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 45 | * `Tkinter 8.5 reference: a GUI for Python <https://www.tkdocs.com/shipman/>`_ |
| 46 | Reference documentation for Tkinter 8.5 detailing available classes, methods, and options. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 47 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 48 | Tcl/Tk Resources: |
| Andrew Svetlov | e708a8a | 2012-07-26 17:02:57 +0300 | [diff] [blame] | 49 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 50 | * `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_ |
| 51 | Comprehensive reference to each of the underlying Tcl/Tk commands used by Tkinter. |
| Andrew Svetlov | e708a8a | 2012-07-26 17:02:57 +0300 | [diff] [blame] | 52 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 53 | * `Tcl/Tk Home Page <https://www.tcl.tk>`_ |
| 54 | Additional documentation, and links to Tcl/Tk core development. |
| Andrew Svetlov | e708a8a | 2012-07-26 17:02:57 +0300 | [diff] [blame] | 55 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 56 | Books: |
| Andrew Svetlov | e708a8a | 2012-07-26 17:02:57 +0300 | [diff] [blame] | 57 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 58 | * `Modern Tkinter for Busy Python Developers <https://tkdocs.com/book.html>`_ |
| 59 | By Mark Roseman. (ISBN 978-1999149567) |
| Andrew Svetlov | e708a8a | 2012-07-26 17:02:57 +0300 | [diff] [blame] | 60 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 61 | * `Python and Tkinter Programming <https://www.packtpub.com/product/python-gui-programming-with-tkinter/9781788835886>`_ |
| 62 | By Alan Moore. (ISBN 978-1788835886) |
| Andrés Delfino | 67a8f4f | 2018-04-25 14:53:58 -0300 | [diff] [blame] | 63 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 64 | * `Programming Python <http://learning-python.com/about-pp4e.html>`_ |
| 65 | By Mark Lutz; has excellent coverage of Tkinter. (ISBN 978-0596158101) |
| Andrés Delfino | 67a8f4f | 2018-04-25 14:53:58 -0300 | [diff] [blame] | 66 | |
| Łukasz Langa | 8e90f15 | 2021-08-22 21:04:57 +0200 | [diff] [blame] | 67 | * `Tcl and the Tk Toolkit (2nd edition) <https://www.amazon.com/exec/obidos/ASIN/032133633X>`_ |
| 68 | By John Ousterhout, inventor of Tcl/Tk, and Ken Jones; does not cover Tkinter. (ISBN 978-0321336330) |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 69 | |
| 70 | |
| Miss Islington (bot) | 2666d70 | 2021-08-11 10:16:10 -0700 | [diff] [blame] | 71 | Architecture |
| 72 | ------------ |
| 73 | |
| 74 | Tcl/Tk is not a single library but rather consists of a few distinct |
| Miss Islington (bot) | e479510 | 2021-08-23 13:08:19 -0700 | [diff] [blame] | 75 | modules, each with separate functionality and its own official |
| Miss Islington (bot) | 2666d70 | 2021-08-11 10:16:10 -0700 | [diff] [blame] | 76 | documentation. Python's binary releases also ship an add-on module |
| 77 | together with it. |
| 78 | |
| 79 | Tcl |
| 80 | Tcl is a dynamic interpreted programming language, just like Python. Though |
| 81 | it can be used on its own as a general-purpose programming language, it is |
| 82 | most commonly embedded into C applications as a scripting engine or an |
| 83 | interface to the Tk toolkit. The Tcl library has a C interface to |
| 84 | create and manage one or more instances of a Tcl interpreter, run Tcl |
| 85 | commands and scripts in those instances, and add custom commands |
| 86 | implemented in either Tcl or C. Each interpreter has an event queue, |
| 87 | and there are facilities to send events to it and process them. |
| 88 | Unlike Python, Tcl's execution model is designed around cooperative |
| 89 | multitasking, and Tkinter bridges this difference |
| 90 | (see `Threading model`_ for details). |
| 91 | |
| 92 | Tk |
| 93 | Tk is a `Tcl package <http://wiki.tcl.tk/37432>`_ implemented in C |
| 94 | that adds custom commands to create and manipulate GUI widgets. Each |
| 95 | :class:`Tk` object embeds its own Tcl interpreter instance with Tk loaded into |
| 96 | it. Tk's widgets are very customizable, though at the cost of a dated appearance. |
| 97 | Tk uses Tcl's event queue to generate and process GUI events. |
| 98 | |
| 99 | Ttk |
| 100 | Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better |
| 101 | appearance on different platforms than many of the classic Tk widgets. |
| 102 | Ttk is distributed as part of Tk, starting with Tk version 8.5. Python |
| 103 | bindings are provided in a separate module, :mod:`tkinter.ttk`. |
| 104 | |
| Miss Islington (bot) | e479510 | 2021-08-23 13:08:19 -0700 | [diff] [blame] | 105 | Internally, Tk and Ttk use facilities of the underlying operating system, |
| 106 | i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows. |
| 107 | |
| 108 | When your Python application uses a class in Tkinter, e.g., to create a widget, |
| 109 | the :mod:`tkinter` module first assembles a Tcl/Tk command string. It passes that |
| 110 | Tcl command string to an internal :mod:`_tkinter` binary module, which then |
| 111 | calls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the |
| 112 | Tk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI. |
| Miss Islington (bot) | 2666d70 | 2021-08-11 10:16:10 -0700 | [diff] [blame] | 113 | |
| 114 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 115 | Tkinter Modules |
| 116 | --------------- |
| 117 | |
| Miss Islington (bot) | 4d1e74f | 2021-08-22 12:04:24 -0700 | [diff] [blame] | 118 | Support for Tkinter is spread across several modules. Most applications will need the |
| 119 | main :mod:`tkinter` module, as well as the :mod:`tkinter.ttk` module, which provides |
| 120 | the modern themed widget set and API:: |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 121 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 123 | from tkinter import * |
| Miss Islington (bot) | 4d1e74f | 2021-08-22 12:04:24 -0700 | [diff] [blame] | 124 | from tkinter import ttk |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 125 | |
| 126 | |
| 127 | .. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1) |
| 128 | |
| 129 | The :class:`Tk` class is instantiated without arguments. This creates a toplevel |
| 130 | widget of Tk which usually is the main window of an application. Each instance |
| 131 | has its own associated Tcl interpreter. |
| 132 | |
| Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 133 | .. FIXME: The following keyword arguments are currently recognized: |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 134 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 135 | |
| 136 | .. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0) |
| 137 | |
| 138 | The :func:`Tcl` function is a factory function which creates an object much like |
| 139 | that created by the :class:`Tk` class, except that it does not initialize the Tk |
| 140 | subsystem. This is most often useful when driving the Tcl interpreter in an |
| 141 | environment where one doesn't want to create extraneous toplevel windows, or |
| 142 | where one cannot (such as Unix/Linux systems without an X server). An object |
| 143 | created by the :func:`Tcl` object can have a Toplevel window created (and the Tk |
| 144 | subsystem initialized) by calling its :meth:`loadtk` method. |
| 145 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 146 | |
| Miss Islington (bot) | 4d1e74f | 2021-08-22 12:04:24 -0700 | [diff] [blame] | 147 | The modules that provide Tk support include: |
| 148 | |
| 149 | :mod:`tkinter` |
| 150 | Main Tkinter module. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 151 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 152 | :mod:`tkinter.colorchooser` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 153 | Dialog to let the user choose a color. |
| 154 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 155 | :mod:`tkinter.commondialog` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 156 | Base class for the dialogs defined in the other modules listed here. |
| 157 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 158 | :mod:`tkinter.filedialog` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 159 | Common dialogs to allow the user to specify a file to open or save. |
| 160 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 161 | :mod:`tkinter.font` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 162 | Utilities to help work with fonts. |
| 163 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 164 | :mod:`tkinter.messagebox` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 165 | Access to standard Tk dialog boxes. |
| 166 | |
| Nikhil | 80428ed | 2019-09-10 01:55:34 -0700 | [diff] [blame] | 167 | :mod:`tkinter.scrolledtext` |
| 168 | Text widget with a vertical scroll bar built in. |
| 169 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 170 | :mod:`tkinter.simpledialog` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 171 | Basic dialogs and convenience functions. |
| 172 | |
| Miss Islington (bot) | 4d1e74f | 2021-08-22 12:04:24 -0700 | [diff] [blame] | 173 | :mod:`tkinter.ttk` |
| 174 | Themed widget set introduced in Tk 8.5, providing modern alternatives |
| 175 | for many of the classic widgets in the main :mod:`tkinter` module. |
| 176 | |
| 177 | Additional modules: |
| 178 | |
| 179 | :mod:`_tkinter` |
| 180 | A binary module that contains the low-level interface to Tcl/Tk. |
| 181 | It is automatically imported by the main :mod:`tkinter` module, |
| 182 | and should never be used directly by application programmers. |
| 183 | It is usually a shared library (or DLL), but might in some cases be |
| 184 | statically linked with the Python interpreter. |
| 185 | |
| 186 | :mod:`idlelib` |
| 187 | Python's Integrated Development and Learning Environment (IDLE). Based |
| 188 | on :mod:`tkinter`. |
| 189 | |
| 190 | :mod:`tkinter.constants` |
| 191 | Symbolic constants that can be used in place of strings when passing |
| 192 | various parameters to Tkinter calls. Automatically imported by the |
| 193 | main :mod:`tkinter` module. |
| 194 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 195 | :mod:`tkinter.dnd` |
| Miss Islington (bot) | 4d1e74f | 2021-08-22 12:04:24 -0700 | [diff] [blame] | 196 | (experimental) Drag-and-drop support for :mod:`tkinter`. This will |
| 197 | become deprecated when it is replaced with the Tk DND. |
| 198 | |
| 199 | :mod:`tkinter.tix` |
| 200 | (deprecated) An older third-party Tcl/Tk package that adds several new |
| 201 | widgets. Better alternatives for most can be found in :mod:`tkinter.ttk`. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 202 | |
| Georg Brandl | 23d11d3 | 2008-09-21 07:50:52 +0000 | [diff] [blame] | 203 | :mod:`turtle` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 204 | Turtle graphics in a Tk window. |
| 205 | |
| 206 | |
| 207 | Tkinter Life Preserver |
| 208 | ---------------------- |
| 209 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | This section is not designed to be an exhaustive tutorial on either Tk or |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 211 | Tkinter. For that, refer to one of the external resources noted earlier. |
| 212 | Instead, this section provides a very quick orientation to what a Tkinter |
| 213 | application looks like, identifies foundational Tk concepts, and |
| 214 | explains how the Tkinter wrapper is structured. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 215 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 216 | The remainder of this section will help you to identify the classes, |
| 217 | methods, and options you'll need in your Tkinter application, and where to |
| 218 | find more detailed documentation on them, including in the official Tcl/Tk |
| 219 | reference manual. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 220 | |
| 221 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 222 | A Hello World Program |
| 223 | ^^^^^^^^^^^^^^^^^^^^^ |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 224 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 225 | We'll start by walking through a "Hello World" application in Tkinter. This |
| 226 | isn't the smallest one we could write, but has enough to illustrate some |
| 227 | key concepts you'll need to know. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 228 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 229 | :: |
| 230 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 231 | from tkinter import * |
| 232 | from tkinter import ttk |
| 233 | root = Tk() |
| 234 | frm = ttk.Frame(root, padding=10) |
| 235 | frm.grid() |
| 236 | ttk.Label(frm, text="Hello World!").grid(column=0, row=0) |
| 237 | ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0) |
| 238 | root.mainloop() |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 239 | |
| 240 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 241 | After the imports, the next line creates an instance of the :class:`Tk` class, |
| 242 | which initializes Tk and creates its associated Tcl interpreter. It also |
| 243 | creates a toplevel window, known as the root window, which serves as the main |
| 244 | window of the application. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 245 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 246 | The following line creates a frame widget, which in this case will contain |
| 247 | a label and a button we'll create next. The frame is fit inside the root |
| 248 | window. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 250 | The next line creates a label widget holding a static text string. The |
| 251 | :meth:`grid` method is used to specify the relative layout (position) of the |
| 252 | label within its containing frame widget, similar to how tables in HTML work. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 253 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 254 | A button widget is then created, and placed to the right of the label. When |
| 255 | pressed, it will call the :meth:`destroy` method of the root window. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 256 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 257 | Finally, the :meth:`mainloop` method puts everything on the display, and |
| 258 | responds to user input until the program terminates. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 259 | |
| 260 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 261 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 262 | Important Tk Concepts |
| 263 | ^^^^^^^^^^^^^^^^^^^^^ |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 264 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 265 | Even this simple program illustrates the following key Tk concepts: |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 266 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 267 | widgets |
| 268 | A Tkinter user interface is made up of individual *widgets*. Each widget is |
| 269 | represented as a Python object, instantiated from classes like |
| 270 | :class:`ttk.Frame`, :class:`ttk.Label`, and :class:`ttk.Button`. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 271 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 272 | widget hierarchy |
| 273 | Widgets are arranged in a *hierarchy*. The label and button were contained |
| 274 | within a frame, which in turn was contained within the root window. When |
| 275 | creating each *child* widget, its *parent* widget is passed as the first |
| 276 | argument to the widget constructor. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 277 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 278 | configuration options |
| 279 | Widgets have *configuration options*, which modify their appearance and |
| 280 | behavior, such as the text to display in a label or button. Different |
| 281 | classes of widgets will have different sets of options. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 282 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 283 | geometry management |
| 284 | Widgets aren't automatically added to the user interface when they are |
| 285 | created. A *geometry manager* like ``grid`` controls where in the |
| 286 | user interface they are placed. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 287 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 288 | event loop |
| 289 | Tkinter reacts to user input, changes from your program, and even refreshes |
| 290 | the display only when actively running an *event loop*. If your program |
| 291 | isn't running the event loop, your user interface won't update. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 292 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 293 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 294 | Understanding How Tkinter Wraps Tcl/Tk |
| 295 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 297 | When your application uses Tkinter's classes and methods, internally Tkinter |
| 298 | is assembling strings representing Tcl/Tk commands, and executing those |
| 299 | commands in the Tcl interpreter attached to your applicaton's :class:`Tk` |
| 300 | instance. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 301 | |
| Miss Islington (bot) | 4673dc2 | 2021-08-23 15:52:02 -0700 | [diff] [blame] | 302 | Whether it's trying to navigate reference documentation, trying to find |
| 303 | the right method or option, adapting some existing code, or debugging your |
| 304 | Tkinter application, there are times that it will be useful to understand |
| 305 | what those underlying Tcl/Tk commands look like. |
| 306 | |
| 307 | To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter |
| 308 | script above. |
| 309 | |
| 310 | :: |
| 311 | |
| 312 | ttk::frame .frm -padding 10 |
| 313 | grid .frm |
| 314 | grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0 |
| 315 | grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0 |
| 316 | |
| 317 | |
| 318 | Tcl's syntax is similar to many shell languages, where the first word is the |
| 319 | command to be executed, with arguments to that command following it, separated |
| 320 | by spaces. Without getting into too many details, notice the following: |
| 321 | |
| 322 | * The commands used to create widgets (like ``ttk::frame``) correspond to |
| 323 | widget classes in Tkinter. |
| 324 | |
| 325 | * Tcl widget options (like ``-text``) correspond to keyword arguments in |
| 326 | Tkinter. |
| 327 | |
| 328 | * Widgets are referred to by a *pathname* in Tcl (like ``.frm.btn``), |
| 329 | whereas Tkinter doesn't use names but object references. |
| 330 | |
| 331 | * A widget's place in the widget hierarchy is encoded in its (hierarchical) |
| 332 | pathname, which uses a ``.`` (dot) as a path separator. The pathname for |
| 333 | the root window is just ``.`` (dot). In Tkinter, the hierarchy is defined |
| 334 | not by pathname but by specifying the parent widget when creating each |
| 335 | child widget. |
| 336 | |
| 337 | * Operations which are implemented as separate *commands* in Tcl (like |
| 338 | ``grid`` or ``destroy``) are represented as *methods* on Tkinter widget |
| 339 | objects. As you'll see shortly, at other times Tcl uses what appear to be |
| 340 | method calls on widget objects, which more closely mirror what would is |
| 341 | used in Tkinter. |
| 342 | |
| 343 | |
| 344 | How do I...? What option does...? |
| 345 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 346 | |
| 347 | If you're not sure how to do something in Tkinter, and you can't immediately |
| 348 | find it in the tutorial or reference documentation you're using, there are a |
| 349 | few strategies that can be helpful. |
| 350 | |
| 351 | First, remember that the details of how individual widgets work may vary |
| 352 | across different versions of both Tkinter and Tcl/Tk. If you're searching |
| 353 | documentation, make sure it corresponds to the Python and Tcl/Tk versions |
| 354 | installed on your system. |
| 355 | |
| 356 | When searching for how to use an API, it helps to know the exact name of the |
| 357 | class, option, or method that you're using. Introspection, either in an |
| 358 | interactive Python shell or with :func:`print`, can help you identify what |
| 359 | you need. |
| 360 | |
| 361 | To find out what configuration options are available on any widget, call its |
| 362 | :meth:`configure` method, which returns a dictionary containing a variety of |
| 363 | information about each object, including its default and current values. Use |
| 364 | :meth:`keys` to get just the names of each option. |
| 365 | |
| 366 | :: |
| 367 | |
| 368 | btn = ttk.Button(frm, ...) |
| 369 | print(btn.configure().keys()) |
| 370 | |
| 371 | As most widgets have many configuration options in common, it can be useful |
| 372 | to find out which are specific to a particular widget class. Comparing the |
| 373 | list of options to that of a simpler widget, like a frame, is one way to |
| 374 | do that. |
| 375 | |
| 376 | :: |
| 377 | |
| 378 | print(set(btn.configure().keys()) - set(frm.configure().keys())) |
| 379 | |
| 380 | Similarly, you can find the available methods for a widget object using the |
| 381 | standard :func:`dir` function. If you try it, you'll see there are over 200 |
| 382 | common widget methods, so again identifying those specific to a widget class |
| 383 | is helpful. |
| 384 | |
| 385 | :: |
| 386 | |
| 387 | print(dir(btn)) |
| 388 | print(set(dir(btn)) - set(dir(frm))) |
| 389 | |
| 390 | |
| 391 | Navigating the Tcl/Tk Reference Manual |
| 392 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 393 | |
| 394 | As noted, the official `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_ |
| 395 | reference manual (man pages) is often the most accurate description of what |
| 396 | specific operations on widgets do. Even when you know the name of the option |
| 397 | or method that you need, you may still have a few places to look. |
| 398 | |
| 399 | While all operations in Tkinter are implemented as method calls on widget |
| 400 | objects, you've seen that many Tcl/Tk operations appear as commands that |
| 401 | take a widget pathname as its first parameter, followed by optional |
| 402 | parameters, e.g. |
| 403 | |
| 404 | :: |
| 405 | |
| 406 | destroy . |
| 407 | grid .frm.btn -column 0 -row 0 |
| 408 | |
| 409 | Others, however, look more like methods called on a widget object (in fact, |
| 410 | when you create a widget in Tcl/Tk, it creates a Tcl command with the name |
| 411 | of the widget pathname, with the first parameter to that command being the |
| 412 | name of a method to call). |
| 413 | |
| 414 | :: |
| 415 | |
| 416 | .frm.btn invoke |
| 417 | .frm.lbl configure -text "Goodbye" |
| 418 | |
| 419 | |
| 420 | In the official Tcl/Tk reference documentation, you'll find most operations |
| 421 | that look like method calls on the man page for a specific widget (e.g., |
| 422 | you'll find the :meth:`invoke` method on the |
| 423 | `ttk::button <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_button.htm>`_ |
| 424 | man page), while functions that take a widget as a parameter often have |
| 425 | their own man page (e.g., |
| 426 | `grid <https://www.tcl.tk/man/tcl8.6/TkCmd/grid.htm>`_). |
| 427 | |
| 428 | You'll find many common options and methods in the |
| 429 | `options <https://www.tcl.tk/man/tcl8.6/TkCmd/options.htm>`_ or |
| 430 | `ttk::widget <https://www.tcl.tk/man/tcl8.6/TkCmd/ttk_widget.htm>`_ man |
| 431 | pages, while others are found in the man page for a specific widget class. |
| 432 | |
| 433 | You'll also find that many Tkinter methods have compound names, e.g., |
| 434 | :func:`winfo_x`, :func:`winfo_height`, :func:`winfo_viewable`. You'd find |
| 435 | documentation for all of these in the |
| 436 | `winfo <https://www.tcl.tk/man/tcl8.6/TkCmd/winfo.htm>`_ man page. |
| 437 | |
| 438 | .. note:: |
| 439 | Somewhat confusingly, there are also methods on all Tkinter widgets |
| 440 | that don't actually operate on the widget, but operate at a global |
| 441 | scope, independent of any widget. Examples are methods for accessing |
| 442 | the clipboard or the system bell. (They happen to be implemented as |
| 443 | methods in the base :class:`Widget` class that all Tkinter widgets |
| 444 | inherit from). |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 445 | |
| 446 | |
| Miss Islington (bot) | 2666d70 | 2021-08-11 10:16:10 -0700 | [diff] [blame] | 447 | Threading model |
| 448 | --------------- |
| 449 | |
| 450 | Python and Tcl/Tk have very different threading models, which :mod:`tkinter` |
| 451 | tries to bridge. If you use threads, you may need to be aware of this. |
| 452 | |
| 453 | A Python interpreter may have many threads associated with it. In Tcl, multiple |
| 454 | threads can be created, but each thread has a separate Tcl interpreter instance |
| 455 | associated with it. Threads can also create more than one interpreter instance, |
| 456 | though each interpreter instance can be used only by the one thread that created it. |
| 457 | |
| 458 | Each :class:`Tk` object created by :mod:`tkinter` contains a Tcl interpreter. |
| 459 | It also keeps track of which thread created that interpreter. Calls to |
| 460 | :mod:`tkinter` can be made from any Python thread. Internally, if a call comes |
| 461 | from a thread other than the one that created the :class:`Tk` object, an event |
| 462 | is posted to the interpreter's event queue, and when executed, the result is |
| 463 | returned to the calling Python thread. |
| 464 | |
| 465 | Tcl/Tk applications are normally event-driven, meaning that after initialization, |
| 466 | the interpreter runs an event loop (i.e. :func:`Tk.mainloop`) and responds to events. |
| 467 | Because it is single-threaded, event handlers must respond quickly, otherwise they |
| 468 | will block other events from being processed. To avoid this, any long-running |
| 469 | computations should not run in an event handler, but are either broken into smaller |
| 470 | pieces using timers, or run in another thread. This is different from many GUI |
| 471 | toolkits where the GUI runs in a completely separate thread from all application |
| 472 | code including event handlers. |
| 473 | |
| 474 | If the Tcl interpreter is not running the event loop and processing events, any |
| 475 | :mod:`tkinter` calls made from threads other than the one running the Tcl |
| 476 | interpreter will fail. |
| 477 | |
| 478 | A number of special cases exist: |
| 479 | |
| 480 | * Tcl/Tk libraries can be built so they are not thread-aware. In this case, |
| 481 | :mod:`tkinter` calls the library from the originating Python thread, even |
| 482 | if this is different than the thread that created the Tcl interpreter. A global |
| 483 | lock ensures only one call occurs at a time. |
| 484 | |
| 485 | * While :mod:`tkinter` allows you to create more than one instance of a :class:`Tk` |
| 486 | object (with its own interpreter), all interpreters that are part of the same |
| 487 | thread share a common event queue, which gets ugly fast. In practice, don't create |
| 488 | more than one instance of :class:`Tk` at a time. Otherwise, it's best to create |
| 489 | them in separate threads and ensure you're running a thread-aware Tcl/Tk build. |
| 490 | |
| 491 | * Blocking event handlers are not the only way to prevent the Tcl interpreter from |
| 492 | reentering the event loop. It is even possible to run multiple nested event loops |
| 493 | or abandon the event loop entirely. If you're doing anything tricky when it comes |
| 494 | to events or threads, be aware of these possibilities. |
| 495 | |
| 496 | * There are a few select :mod:`tkinter` functions that presently work only when |
| 497 | called from the thread that created the Tcl interpreter. |
| 498 | |
| 499 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 500 | Handy Reference |
| 501 | --------------- |
| 502 | |
| 503 | |
| 504 | .. _tkinter-setting-options: |
| 505 | |
| 506 | Setting Options |
| 507 | ^^^^^^^^^^^^^^^ |
| 508 | |
| 509 | Options control things like the color and border width of a widget. Options can |
| 510 | be set in three ways: |
| 511 | |
| 512 | At object creation time, using keyword arguments |
| 513 | :: |
| 514 | |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 515 | fred = Button(self, fg="red", bg="blue") |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 516 | |
| 517 | After object creation, treating the option name like a dictionary index |
| 518 | :: |
| 519 | |
| 520 | fred["fg"] = "red" |
| 521 | fred["bg"] = "blue" |
| 522 | |
| 523 | Use the config() method to update multiple attrs subsequent to object creation |
| 524 | :: |
| 525 | |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 526 | fred.config(fg="red", bg="blue") |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 527 | |
| 528 | For a complete explanation of a given option and its behavior, see the Tk man |
| 529 | pages for the widget in question. |
| 530 | |
| 531 | Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS" |
| 532 | for each widget. The former is a list of options that are common to many |
| 533 | widgets, the latter are the options that are idiosyncratic to that particular |
| 534 | widget. The Standard Options are documented on the :manpage:`options(3)` man |
| 535 | page. |
| 536 | |
| 537 | No distinction between standard and widget-specific options is made in this |
| 538 | document. Some options don't apply to some kinds of widgets. Whether a given |
| 539 | widget responds to a particular option depends on the class of the widget; |
| 540 | buttons have a ``command`` option, labels do not. |
| 541 | |
| 542 | The options supported by a given widget are listed in that widget's man page, or |
| 543 | can be queried at runtime by calling the :meth:`config` method without |
| 544 | arguments, or by calling the :meth:`keys` method on that widget. The return |
| 545 | value of these calls is a dictionary whose key is the name of the option as a |
| 546 | string (for example, ``'relief'``) and whose values are 5-tuples. |
| 547 | |
| 548 | Some options, like ``bg`` are synonyms for common options with long names |
| 549 | (``bg`` is shorthand for "background"). Passing the ``config()`` method the name |
| 550 | of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed |
| 551 | back will contain the name of the synonym and the "real" option (such as |
| 552 | ``('bg', 'background')``). |
| 553 | |
| 554 | +-------+---------------------------------+--------------+ |
| 555 | | Index | Meaning | Example | |
| 556 | +=======+=================================+==============+ |
| 557 | | 0 | option name | ``'relief'`` | |
| 558 | +-------+---------------------------------+--------------+ |
| 559 | | 1 | option name for database lookup | ``'relief'`` | |
| 560 | +-------+---------------------------------+--------------+ |
| 561 | | 2 | option class for database | ``'Relief'`` | |
| 562 | | | lookup | | |
| 563 | +-------+---------------------------------+--------------+ |
| 564 | | 3 | default value | ``'raised'`` | |
| 565 | +-------+---------------------------------+--------------+ |
| 566 | | 4 | current value | ``'groove'`` | |
| 567 | +-------+---------------------------------+--------------+ |
| 568 | |
| 569 | Example:: |
| 570 | |
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 571 | >>> print(fred.config()) |
| Serhiy Storchaka | f47036c | 2013-12-24 11:04:36 +0200 | [diff] [blame] | 572 | {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')} |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 573 | |
| 574 | Of course, the dictionary printed will include all the options available and |
| 575 | their values. This is meant only as an example. |
| 576 | |
| 577 | |
| 578 | The Packer |
| 579 | ^^^^^^^^^^ |
| 580 | |
| 581 | .. index:: single: packing (widgets) |
| 582 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 583 | The packer is one of Tk's geometry-management mechanisms. Geometry managers |
| Nathan M | ecaf949 | 2020-08-02 22:13:03 -0400 | [diff] [blame] | 584 | are used to specify the relative positioning of widgets within their container - |
| 585 | their mutual *master*. In contrast to the more cumbersome *placer* (which is |
| 586 | used less commonly, and we do not cover here), the packer takes qualitative |
| 587 | relationship specification - *above*, *to the left of*, *filling*, etc - and |
| 588 | works everything out to determine the exact placement coordinates for you. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 589 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 590 | The size of any *master* widget is determined by the size of the "slave widgets" |
| 591 | inside. The packer is used to control where slave widgets appear inside the |
| 592 | master into which they are packed. You can pack widgets into frames, and frames |
| 593 | into other frames, in order to achieve the kind of layout you desire. |
| 594 | Additionally, the arrangement is dynamically adjusted to accommodate incremental |
| 595 | changes to the configuration, once it is packed. |
| 596 | |
| 597 | Note that widgets do not appear until they have had their geometry specified |
| 598 | with a geometry manager. It's a common early mistake to leave out the geometry |
| 599 | specification, and then be surprised when the widget is created but nothing |
| 600 | appears. A widget will appear only after it has had, for example, the packer's |
| 601 | :meth:`pack` method applied to it. |
| 602 | |
| 603 | The pack() method can be called with keyword-option/value pairs that control |
| 604 | where the widget is to appear within its container, and how it is to behave when |
| 605 | the main application window is resized. Here are some examples:: |
| 606 | |
| 607 | fred.pack() # defaults to side = "top" |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 608 | fred.pack(side="left") |
| 609 | fred.pack(expand=1) |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 610 | |
| 611 | |
| 612 | Packer Options |
| 613 | ^^^^^^^^^^^^^^ |
| 614 | |
| 615 | For more extensive information on the packer and the options that it can take, |
| 616 | see the man pages and page 183 of John Ousterhout's book. |
| 617 | |
| Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 618 | anchor |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 619 | Anchor type. Denotes where the packer is to place each slave in its parcel. |
| 620 | |
| 621 | expand |
| 622 | Boolean, ``0`` or ``1``. |
| 623 | |
| 624 | fill |
| 625 | Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``. |
| 626 | |
| 627 | ipadx and ipady |
| 628 | A distance - designating internal padding on each side of the slave widget. |
| 629 | |
| 630 | padx and pady |
| 631 | A distance - designating external padding on each side of the slave widget. |
| 632 | |
| 633 | side |
| 634 | Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``. |
| 635 | |
| 636 | |
| 637 | Coupling Widget Variables |
| 638 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 639 | |
| 640 | The current-value setting of some widgets (like text entry widgets) can be |
| 641 | connected directly to application variables by using special options. These |
| 642 | options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and |
| 643 | ``value``. This connection works both ways: if the variable changes for any |
| 644 | reason, the widget it's connected to will be updated to reflect the new value. |
| 645 | |
| Georg Brandl | ac6060c | 2008-05-17 18:44:45 +0000 | [diff] [blame] | 646 | Unfortunately, in the current implementation of :mod:`tkinter` it is not |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 647 | possible to hand over an arbitrary Python variable to a widget through a |
| 648 | ``variable`` or ``textvariable`` option. The only kinds of variables for which |
| 649 | this works are variables that are subclassed from a class called Variable, |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 650 | defined in :mod:`tkinter`. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 651 | |
| 652 | There are many useful subclasses of Variable already defined: |
| 653 | :class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and |
| 654 | :class:`BooleanVar`. To read the current value of such a variable, call the |
| Georg Brandl | 502d9a5 | 2009-07-26 15:02:41 +0000 | [diff] [blame] | 655 | :meth:`get` method on it, and to change its value you call the :meth:`!set` |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 656 | method. If you follow this protocol, the widget will always track the value of |
| 657 | the variable, with no further intervention on your part. |
| 658 | |
| 659 | For example:: |
| 660 | |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 661 | import tkinter as tk |
| 662 | |
| 663 | class App(tk.Frame): |
| 664 | def __init__(self, master): |
| Berker Peksag | 3093bf1 | 2016-07-14 07:32:43 +0300 | [diff] [blame] | 665 | super().__init__(master) |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 666 | self.pack() |
| 667 | |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 668 | self.entrythingy = tk.Entry() |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 669 | self.entrythingy.pack() |
| 670 | |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 671 | # Create the application variable. |
| 672 | self.contents = tk.StringVar() |
| 673 | # Set it to some value. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 674 | self.contents.set("this is a variable") |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 675 | # Tell the entry widget to watch this variable. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 676 | self.entrythingy["textvariable"] = self.contents |
| 677 | |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 678 | # Define a callback for when the user hits return. |
| 679 | # It prints the current value of the variable. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 680 | self.entrythingy.bind('<Key-Return>', |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 681 | self.print_contents) |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 682 | |
| 683 | def print_contents(self, event): |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 684 | print("Hi. The current entry content is:", |
| Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 685 | self.contents.get()) |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 686 | |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 687 | root = tk.Tk() |
| 688 | myapp = App(root) |
| 689 | myapp.mainloop() |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 690 | |
| 691 | The Window Manager |
| 692 | ^^^^^^^^^^^^^^^^^^ |
| 693 | |
| 694 | .. index:: single: window manager (widgets) |
| 695 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 696 | In Tk, there is a utility command, ``wm``, for interacting with the window |
| 697 | 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] | 698 | placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 699 | been implemented as methods on the :class:`Wm` class. Toplevel widgets are |
| 700 | subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods |
| 701 | directly. |
| 702 | |
| 703 | To get at the toplevel window that contains a given widget, you can often just |
| 704 | refer to the widget's master. Of course if the widget has been packed inside of |
| 705 | a frame, the master won't represent a toplevel window. To get at the toplevel |
| 706 | window that contains an arbitrary widget, you can call the :meth:`_root` method. |
| 707 | This method begins with an underscore to denote the fact that this function is |
| 708 | part of the implementation, and not an interface to Tk functionality. |
| 709 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 710 | Here are some examples of typical usage:: |
| 711 | |
| Berker Peksag | 3093bf1 | 2016-07-14 07:32:43 +0300 | [diff] [blame] | 712 | import tkinter as tk |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 713 | |
| Berker Peksag | 3093bf1 | 2016-07-14 07:32:43 +0300 | [diff] [blame] | 714 | class App(tk.Frame): |
| 715 | def __init__(self, master=None): |
| 716 | super().__init__(master) |
| 717 | self.pack() |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 718 | |
| 719 | # create the application |
| 720 | myapp = App() |
| 721 | |
| 722 | # |
| 723 | # here are method calls to the window manager class |
| 724 | # |
| 725 | myapp.master.title("My Do-Nothing Application") |
| 726 | myapp.master.maxsize(1000, 400) |
| 727 | |
| 728 | # start the program |
| 729 | myapp.mainloop() |
| 730 | |
| 731 | |
| 732 | Tk Option Data Types |
| 733 | ^^^^^^^^^^^^^^^^^^^^ |
| 734 | |
| 735 | .. index:: single: Tk Option Data Types |
| 736 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 737 | anchor |
| 738 | Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``, |
| 739 | ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``. |
| 740 | |
| 741 | bitmap |
| 742 | There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``, |
| 743 | ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``, |
| 744 | ``'warning'``. To specify an X bitmap filename, give the full path to the file, |
| 745 | preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``. |
| 746 | |
| 747 | boolean |
| Serhiy Storchaka | a4d170d | 2013-12-23 18:20:51 +0200 | [diff] [blame] | 748 | You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 749 | |
| 750 | callback |
| 751 | This is any Python function that takes no arguments. For example:: |
| 752 | |
| 753 | def print_it(): |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 754 | print("hi there") |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 755 | fred["command"] = print_it |
| 756 | |
| 757 | color |
| 758 | Colors can be given as the names of X colors in the rgb.txt file, or as strings |
| Miss Islington (bot) | c5a987b | 2022-02-14 12:10:05 -0800 | [diff] [blame^] | 759 | representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit: |
| 760 | ``"#RRRGGGBBB"``, or 16 bit: ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 761 | represent any legal hex digit. See page 160 of Ousterhout's book for details. |
| 762 | |
| 763 | cursor |
| 764 | The standard X cursor names from :file:`cursorfont.h` can be used, without the |
| 765 | ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the |
| 766 | string ``"hand2"``. You can also specify a bitmap and mask file of your own. |
| 767 | See page 179 of Ousterhout's book. |
| 768 | |
| 769 | distance |
| 770 | Screen distances can be specified in either pixels or absolute distances. |
| 771 | Pixels are given as numbers and absolute distances as strings, with the trailing |
| 772 | character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for |
| 773 | millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed |
| 774 | as ``"3.5i"``. |
| 775 | |
| 776 | font |
| 777 | Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with |
| 778 | positive numbers are measured in points; sizes with negative numbers are |
| 779 | measured in pixels. |
| 780 | |
| 781 | geometry |
| 782 | This is a string of the form ``widthxheight``, where width and height are |
| 783 | measured in pixels for most widgets (in characters for widgets displaying text). |
| 784 | For example: ``fred["geometry"] = "200x100"``. |
| 785 | |
| 786 | justify |
| 787 | Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and |
| 788 | ``"fill"``. |
| 789 | |
| 790 | region |
| 791 | This is a string with four space-delimited elements, each of which is a legal |
| 792 | distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and |
| 793 | ``"3c 2c 4c 10.43c"`` are all legal regions. |
| 794 | |
| 795 | relief |
| 796 | Determines what the border style of a widget will be. Legal values are: |
| 797 | ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``. |
| 798 | |
| 799 | scrollcommand |
| Georg Brandl | 502d9a5 | 2009-07-26 15:02:41 +0000 | [diff] [blame] | 800 | This is almost always the :meth:`!set` method of some scrollbar widget, but can |
| Georg Brandl | 59b4472 | 2010-12-30 22:12:40 +0000 | [diff] [blame] | 801 | be any widget method that takes a single argument. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 802 | |
| Nikhil | 80428ed | 2019-09-10 01:55:34 -0700 | [diff] [blame] | 803 | wrap |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 804 | Must be one of: ``"none"``, ``"char"``, or ``"word"``. |
| 805 | |
| Nikhil | 80428ed | 2019-09-10 01:55:34 -0700 | [diff] [blame] | 806 | .. _Bindings-and-Events: |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 807 | |
| 808 | Bindings and Events |
| 809 | ^^^^^^^^^^^^^^^^^^^ |
| 810 | |
| 811 | .. index:: |
| 812 | single: bind (widgets) |
| 813 | single: events (widgets) |
| 814 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 815 | The bind method from the widget command allows you to watch for certain events |
| 816 | and to have a callback function trigger when that event type occurs. The form |
| 817 | of the bind method is:: |
| 818 | |
| 819 | def bind(self, sequence, func, add=''): |
| 820 | |
| 821 | where: |
| 822 | |
| 823 | sequence |
| 824 | is a string that denotes the target kind of event. (See the bind man page and |
| 825 | page 201 of John Ousterhout's book for details). |
| 826 | |
| 827 | func |
| 828 | is a Python function, taking one argument, to be invoked when the event occurs. |
| 829 | An Event instance will be passed as the argument. (Functions deployed this way |
| 830 | are commonly known as *callbacks*.) |
| 831 | |
| 832 | add |
| 833 | is optional, either ``''`` or ``'+'``. Passing an empty string denotes that |
| 834 | this binding is to replace any other bindings that this event is associated |
| 835 | with. Passing a ``'+'`` means that this function is to be added to the list |
| 836 | of functions bound to this event type. |
| 837 | |
| 838 | For example:: |
| 839 | |
| Berker Peksag | 3093bf1 | 2016-07-14 07:32:43 +0300 | [diff] [blame] | 840 | def turn_red(self, event): |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 841 | event.widget["activeforeground"] = "red" |
| 842 | |
| Berker Peksag | 3093bf1 | 2016-07-14 07:32:43 +0300 | [diff] [blame] | 843 | self.button.bind("<Enter>", self.turn_red) |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 844 | |
| 845 | Notice how the widget field of the event is being accessed in the |
| Berker Peksag | 3093bf1 | 2016-07-14 07:32:43 +0300 | [diff] [blame] | 846 | ``turn_red()`` callback. This field contains the widget that caught the X |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 847 | event. The following table lists the other event fields you can access, and how |
| 848 | they are denoted in Tk, which can be useful when referring to the Tk man pages. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 849 | |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 850 | +----+---------------------+----+---------------------+ |
| 851 | | Tk | Tkinter Event Field | Tk | Tkinter Event Field | |
| 852 | +====+=====================+====+=====================+ |
| 853 | | %f | focus | %A | char | |
| 854 | +----+---------------------+----+---------------------+ |
| 855 | | %h | height | %E | send_event | |
| 856 | +----+---------------------+----+---------------------+ |
| 857 | | %k | keycode | %K | keysym | |
| 858 | +----+---------------------+----+---------------------+ |
| 859 | | %s | state | %N | keysym_num | |
| 860 | +----+---------------------+----+---------------------+ |
| 861 | | %t | time | %T | type | |
| 862 | +----+---------------------+----+---------------------+ |
| 863 | | %w | width | %W | widget | |
| 864 | +----+---------------------+----+---------------------+ |
| 865 | | %x | x | %X | x_root | |
| 866 | +----+---------------------+----+---------------------+ |
| 867 | | %y | y | %Y | y_root | |
| 868 | +----+---------------------+----+---------------------+ |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 869 | |
| 870 | |
| 871 | The index Parameter |
| 872 | ^^^^^^^^^^^^^^^^^^^ |
| 873 | |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 874 | A number of widgets require "index" parameters to be passed. These are used to |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 875 | point at a specific place in a Text widget, or to particular characters in an |
| 876 | Entry widget, or to particular menu items in a Menu widget. |
| 877 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 878 | Entry widget indexes (index, view index, etc.) |
| 879 | 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] | 880 | displayed. You can use these :mod:`tkinter` functions to access these special |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 881 | points in text widgets: |
| 882 | |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 883 | Text widget indexes |
| 884 | The index notation for Text widgets is very rich and is best described in the Tk |
| 885 | man pages. |
| 886 | |
| 887 | Menu indexes (menu.invoke(), menu.entryconfig(), etc.) |
| 888 | Some options and methods for menus manipulate specific menu entries. Anytime a |
| 889 | menu index is needed for an option or a parameter, you may pass in: |
| 890 | |
| 891 | * an integer which refers to the numeric position of the entry in the widget, |
| 892 | counted from the top, starting with 0; |
| 893 | |
| Ezio Melotti | 1a263ad | 2010-03-14 09:51:37 +0000 | [diff] [blame] | 894 | * the string ``"active"``, which refers to the menu position that is currently |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 895 | under the cursor; |
| 896 | |
| 897 | * the string ``"last"`` which refers to the last menu item; |
| 898 | |
| 899 | * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted |
| 900 | as a y pixel coordinate in the menu's coordinate system; |
| 901 | |
| 902 | * the string ``"none"``, which indicates no menu entry at all, most often used |
| 903 | with menu.activate() to deactivate all entries, and finally, |
| 904 | |
| 905 | * a text string that is pattern matched against the label of the menu entry, as |
| 906 | scanned from the top of the menu to the bottom. Note that this index type is |
| 907 | considered after all the others, which means that matches for menu items |
| 908 | labelled ``last``, ``active``, or ``none`` may be interpreted as the above |
| 909 | literals, instead. |
| 910 | |
| 911 | |
| 912 | Images |
| 913 | ^^^^^^ |
| 914 | |
| Andrés Delfino | 4b685bf | 2018-04-17 02:34:35 -0300 | [diff] [blame] | 915 | Images of different formats can be created through the corresponding subclass |
| 916 | of :class:`tkinter.Image`: |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 917 | |
| Andrés Delfino | 4b685bf | 2018-04-17 02:34:35 -0300 | [diff] [blame] | 918 | * :class:`BitmapImage` for images in XBM format. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 919 | |
| Andrés Delfino | 4b685bf | 2018-04-17 02:34:35 -0300 | [diff] [blame] | 920 | * :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter |
| 921 | is supported starting with Tk 8.6. |
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 922 | |
| 923 | Either type of image is created through either the ``file`` or the ``data`` |
| 924 | option (other options are available as well). |
| 925 | |
| 926 | The image object can then be used wherever an ``image`` option is supported by |
| 927 | some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a |
| 928 | reference to the image. When the last Python reference to the image object is |
| 929 | deleted, the image data is deleted as well, and Tk will display an empty box |
| 930 | wherever the image was used. |
| Terry Jan Reedy | d986563 | 2015-05-17 14:49:26 -0400 | [diff] [blame] | 931 | |
| Andrés Delfino | b81ca28 | 2018-04-21 09:17:26 -0300 | [diff] [blame] | 932 | .. seealso:: |
| 933 | |
| 934 | The `Pillow <http://python-pillow.org/>`_ package adds support for |
| 935 | formats such as BMP, JPEG, TIFF, and WebP, among others. |
| Terry Jan Reedy | d986563 | 2015-05-17 14:49:26 -0400 | [diff] [blame] | 936 | |
| 937 | .. _tkinter-file-handlers: |
| 938 | |
| 939 | File Handlers |
| 940 | ------------- |
| 941 | |
| 942 | Tk allows you to register and unregister a callback function which will be |
| 943 | called from the Tk mainloop when I/O is possible on a file descriptor. |
| 944 | Only one handler may be registered per file descriptor. Example code:: |
| 945 | |
| 946 | import tkinter |
| 947 | widget = tkinter.Tk() |
| 948 | mask = tkinter.READABLE | tkinter.WRITABLE |
| 949 | widget.tk.createfilehandler(file, mask, callback) |
| 950 | ... |
| 951 | widget.tk.deletefilehandler(file) |
| 952 | |
| 953 | This feature is not available on Windows. |
| 954 | |
| 955 | Since you don't know how many bytes are available for reading, you may not |
| 956 | want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase` |
| 957 | :meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods, |
| 958 | since these will insist on reading a predefined number of bytes. |
| 959 | For sockets, the :meth:`~socket.socket.recv` or |
| 960 | :meth:`~socket.socket.recvfrom` methods will work fine; for other files, |
| 961 | use raw reads or ``os.read(file.fileno(), maxbytecount)``. |
| 962 | |
| 963 | |
| 964 | .. method:: Widget.tk.createfilehandler(file, mask, func) |
| 965 | |
| 966 | Registers the file handler callback function *func*. The *file* argument |
| 967 | may either be an object with a :meth:`~io.IOBase.fileno` method (such as |
| 968 | a file or socket object), or an integer file descriptor. The *mask* |
| 969 | argument is an ORed combination of any of the three constants below. |
| 970 | The callback is called as follows:: |
| 971 | |
| 972 | callback(file, mask) |
| 973 | |
| 974 | |
| 975 | .. method:: Widget.tk.deletefilehandler(file) |
| 976 | |
| 977 | Unregisters a file handler. |
| 978 | |
| 979 | |
| 980 | .. data:: READABLE |
| 981 | WRITABLE |
| 982 | EXCEPTION |
| 983 | |
| Ankit Chandawala | c36dbac | 2020-08-03 05:03:48 +0100 | [diff] [blame] | 984 | Constants used in the *mask* arguments. |