blob: 2d7c02ff49f2e21e4a5369d314688dcc28f2c1f1 [file] [log] [blame]
Georg Brandlac6060c2008-05-17 18:44:45 +00001:mod:`tkinter` --- Python interface to Tcl/Tk
Georg Brandl116aa622007-08-15 14:28:22 +00002=============================================
3
Georg Brandlac6060c2008-05-17 18:44:45 +00004.. module:: tkinter
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Interface to Tcl/Tk for graphical user interfaces
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Guido van Rossum <guido@Python.org>
8
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04009**Source code:** :source:`Lib/tkinter/__init__.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandlac6060c2008-05-17 18:44:45 +000013The :mod:`tkinter` package ("Tk interface") is the standard Python interface to
Miss Islington (bot)61ecd3e2021-08-22 11:54:46 -070014the Tcl/Tk GUI toolkit. Both Tk and :mod:`tkinter` are available on most Unix
15platforms, including macOS, as well as on Windows systems.
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030016
17Running ``python -m tkinter`` from the command line should open a window
18demonstrating a simple Tk interface, letting you know that :mod:`tkinter` is
19properly installed on your system, and also showing what version of Tcl/Tk is
20installed, so you can read the Tcl/Tk documentation specific to that version.
Georg Brandl116aa622007-08-15 14:28:22 +000021
Miss Islington (bot)2666d702021-08-11 10:16:10 -070022Tkinter supports a range of Tcl/Tk versions, built either with or
23without thread support. The official Python binary release bundles Tcl/Tk 8.6
24threaded. See the source code for the :mod:`_tkinter` module
25for more information about supported versions.
26
27Tkinter is not a thin wrapper, but adds a fair amount of its own logic to
28make the experience more pythonic. This documentation will concentrate on these
29additions and changes, and refer to the official Tcl/Tk documentation for
30details that are unchanged.
31
Georg Brandl116aa622007-08-15 14:28:22 +000032.. seealso::
33
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030034 Tkinter documentation:
35
Zachary Ware08863992014-03-18 09:19:18 -050036 `Python Tkinter Resources <https://wiki.python.org/moin/TkInter>`_
Georg Brandl116aa622007-08-15 14:28:22 +000037 The Python Tkinter Topic Guide provides a great deal of information on using Tk
38 from Python and links to other sources of information on Tk.
39
Andrew Svetlove708a8a2012-07-26 17:02:57 +030040 `TKDocs <http://www.tkdocs.com/>`_
41 Extensive tutorial plus friendlier widget pages for some of the widgets.
42
Mark Roseman06d0b8b2020-09-10 13:04:20 -070043 `Tkinter 8.5 reference: a GUI for Python <https://www.tkdocs.com/shipman/>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030044 On-line reference material.
45
46 `Tkinter docs from effbot <http://effbot.org/tkinterbook/>`_
47 Online reference for tkinter supported by effbot.org.
48
Sanyam Khurana338cd832018-01-20 05:55:37 +053049 `Programming Python <http://learning-python.com/about-pp4e.html>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030050 Book by Mark Lutz, has excellent coverage of Tkinter.
51
Sanyam Khurana1b4587a2017-12-06 22:09:33 +053052 `Modern Tkinter for Busy Python Developers <https://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/>`_
Terry Jan Reedy45bc61b2019-07-06 02:31:54 -040053 Book by Mark Roseman about building attractive and modern graphical user interfaces with Python and Tkinter.
Andrew Svetlove708a8a2012-07-26 17:02:57 +030054
Georg Brandl5d941342016-02-26 19:37:12 +010055 `Python and Tkinter Programming <https://www.manning.com/books/python-and-tkinter-programming>`_
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030056 Book by John Grayson (ISBN 1-884777-81-3).
57
58 Tcl/Tk documentation:
59
60 `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
61 Most commands are available as :mod:`tkinter` or :mod:`tkinter.ttk` classes.
62 Change '8.6' to match the version of your Tcl/Tk installation.
63
64 `Tcl/Tk recent man pages <https://www.tcl.tk/doc/>`_
65 Recent Tcl/Tk manuals on www.tcl.tk.
66
Julien Palard7114c652019-05-25 20:02:24 +020067 `ActiveState Tcl Home Page <https://tcl.tk>`_
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030068 The Tk/Tcl development is largely taking place at ActiveState.
69
70 `Tcl and the Tk Toolkit <https://www.amazon.com/exec/obidos/ASIN/020163337X>`_
71 Book by John Ousterhout, the inventor of Tcl.
72
73 `Practical Programming in Tcl and Tk <http://www.beedub.com/book/>`_
74 Brent Welch's encyclopedic book.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76
Miss Islington (bot)2666d702021-08-11 10:16:10 -070077Architecture
78------------
79
80Tcl/Tk is not a single library but rather consists of a few distinct
81modules, each with a separate functionality and its own official
82documentation. Python's binary releases also ship an add-on module
83together with it.
84
85Tcl
86 Tcl is a dynamic interpreted programming language, just like Python. Though
87 it can be used on its own as a general-purpose programming language, it is
88 most commonly embedded into C applications as a scripting engine or an
89 interface to the Tk toolkit. The Tcl library has a C interface to
90 create and manage one or more instances of a Tcl interpreter, run Tcl
91 commands and scripts in those instances, and add custom commands
92 implemented in either Tcl or C. Each interpreter has an event queue,
93 and there are facilities to send events to it and process them.
94 Unlike Python, Tcl's execution model is designed around cooperative
95 multitasking, and Tkinter bridges this difference
96 (see `Threading model`_ for details).
97
98Tk
99 Tk is a `Tcl package <http://wiki.tcl.tk/37432>`_ implemented in C
100 that adds custom commands to create and manipulate GUI widgets. Each
101 :class:`Tk` object embeds its own Tcl interpreter instance with Tk loaded into
102 it. Tk's widgets are very customizable, though at the cost of a dated appearance.
103 Tk uses Tcl's event queue to generate and process GUI events.
104
105Ttk
106 Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better
107 appearance on different platforms than many of the classic Tk widgets.
108 Ttk is distributed as part of Tk, starting with Tk version 8.5. Python
109 bindings are provided in a separate module, :mod:`tkinter.ttk`.
110
111Tix
112 `Tix <https://core.tcl.tk/jenglish/gutter/packages/tix.html>`_ is an older
113 third-party Tcl package, an add-on for Tk that adds several new widgets.
114 Python bindings are found in the :mod:`tkinter.tix` module.
115 It's deprecated in favor of Ttk.
116
117
Georg Brandl116aa622007-08-15 14:28:22 +0000118Tkinter Modules
119---------------
120
Miss Islington (bot)4d1e74f2021-08-22 12:04:24 -0700121Support for Tkinter is spread across several modules. Most applications will need the
122main :mod:`tkinter` module, as well as the :mod:`tkinter.ttk` module, which provides
123the modern themed widget set and API::
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Georg Brandl116aa622007-08-15 14:28:22 +0000125
Georg Brandlac6060c2008-05-17 18:44:45 +0000126 from tkinter import *
Miss Islington (bot)4d1e74f2021-08-22 12:04:24 -0700127 from tkinter import ttk
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129
130.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
131
132 The :class:`Tk` class is instantiated without arguments. This creates a toplevel
133 widget of Tk which usually is the main window of an application. Each instance
134 has its own associated Tcl interpreter.
135
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000136 .. FIXME: The following keyword arguments are currently recognized:
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
140
141 The :func:`Tcl` function is a factory function which creates an object much like
142 that created by the :class:`Tk` class, except that it does not initialize the Tk
143 subsystem. This is most often useful when driving the Tcl interpreter in an
144 environment where one doesn't want to create extraneous toplevel windows, or
145 where one cannot (such as Unix/Linux systems without an X server). An object
146 created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
147 subsystem initialized) by calling its :meth:`loadtk` method.
148
Georg Brandl116aa622007-08-15 14:28:22 +0000149
Miss Islington (bot)4d1e74f2021-08-22 12:04:24 -0700150The modules that provide Tk support include:
151
152:mod:`tkinter`
153 Main Tkinter module.
Georg Brandl116aa622007-08-15 14:28:22 +0000154
Georg Brandlac6060c2008-05-17 18:44:45 +0000155:mod:`tkinter.colorchooser`
Georg Brandl116aa622007-08-15 14:28:22 +0000156 Dialog to let the user choose a color.
157
Georg Brandlac6060c2008-05-17 18:44:45 +0000158:mod:`tkinter.commondialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000159 Base class for the dialogs defined in the other modules listed here.
160
Georg Brandlac6060c2008-05-17 18:44:45 +0000161:mod:`tkinter.filedialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000162 Common dialogs to allow the user to specify a file to open or save.
163
Georg Brandlac6060c2008-05-17 18:44:45 +0000164:mod:`tkinter.font`
Georg Brandl116aa622007-08-15 14:28:22 +0000165 Utilities to help work with fonts.
166
Georg Brandlac6060c2008-05-17 18:44:45 +0000167:mod:`tkinter.messagebox`
Georg Brandl116aa622007-08-15 14:28:22 +0000168 Access to standard Tk dialog boxes.
169
Nikhil80428ed2019-09-10 01:55:34 -0700170:mod:`tkinter.scrolledtext`
171 Text widget with a vertical scroll bar built in.
172
Georg Brandlac6060c2008-05-17 18:44:45 +0000173:mod:`tkinter.simpledialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000174 Basic dialogs and convenience functions.
175
Miss Islington (bot)4d1e74f2021-08-22 12:04:24 -0700176:mod:`tkinter.ttk`
177 Themed widget set introduced in Tk 8.5, providing modern alternatives
178 for many of the classic widgets in the main :mod:`tkinter` module.
179
180Additional modules:
181
182:mod:`_tkinter`
183 A binary module that contains the low-level interface to Tcl/Tk.
184 It is automatically imported by the main :mod:`tkinter` module,
185 and should never be used directly by application programmers.
186 It is usually a shared library (or DLL), but might in some cases be
187 statically linked with the Python interpreter.
188
189:mod:`idlelib`
190 Python's Integrated Development and Learning Environment (IDLE). Based
191 on :mod:`tkinter`.
192
193:mod:`tkinter.constants`
194 Symbolic constants that can be used in place of strings when passing
195 various parameters to Tkinter calls. Automatically imported by the
196 main :mod:`tkinter` module.
197
Georg Brandlac6060c2008-05-17 18:44:45 +0000198:mod:`tkinter.dnd`
Miss Islington (bot)4d1e74f2021-08-22 12:04:24 -0700199 (experimental) Drag-and-drop support for :mod:`tkinter`. This will
200 become deprecated when it is replaced with the Tk DND.
201
202:mod:`tkinter.tix`
203 (deprecated) An older third-party Tcl/Tk package that adds several new
204 widgets. Better alternatives for most can be found in :mod:`tkinter.ttk`.
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Georg Brandl23d11d32008-09-21 07:50:52 +0000206:mod:`turtle`
Georg Brandl116aa622007-08-15 14:28:22 +0000207 Turtle graphics in a Tk window.
208
209
210Tkinter Life Preserver
211----------------------
212
213.. sectionauthor:: Matt Conway
214
215
216This section is not designed to be an exhaustive tutorial on either Tk or
217Tkinter. Rather, it is intended as a stop gap, providing some introductory
218orientation on the system.
219
Georg Brandl116aa622007-08-15 14:28:22 +0000220Credits:
221
Georg Brandl116aa622007-08-15 14:28:22 +0000222* Tk was written by John Ousterhout while at Berkeley.
223
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000224* Tkinter was written by Steen Lumholt and Guido van Rossum.
225
Georg Brandl116aa622007-08-15 14:28:22 +0000226* This Life Preserver was written by Matt Conway at the University of Virginia.
227
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000228* The HTML rendering, and some liberal editing, was produced from a FrameMaker
Georg Brandl116aa622007-08-15 14:28:22 +0000229 version by Ken Manheimer.
230
231* Fredrik Lundh elaborated and revised the class interface descriptions, to get
232 them current with Tk 4.2.
233
234* Mike Clarkson converted the documentation to LaTeX, and compiled the User
235 Interface chapter of the reference manual.
236
237
238How To Use This Section
239^^^^^^^^^^^^^^^^^^^^^^^
240
241This section is designed in two parts: the first half (roughly) covers
242background material, while the second half can be taken to the keyboard as a
243handy reference.
244
245When trying to answer questions of the form "how do I do blah", it is often best
Julien Palardae342cf2017-12-05 06:05:33 +0100246to find out how to do "blah" in straight Tk, and then convert this back into the
Georg Brandlac6060c2008-05-17 18:44:45 +0000247corresponding :mod:`tkinter` call. Python programmers can often guess at the
Georg Brandl116aa622007-08-15 14:28:22 +0000248correct Python command by looking at the Tk documentation. This means that in
249order to use Tkinter, you will have to know a little bit about Tk. This document
250can't fulfill that role, so the best we can do is point you to the best
251documentation that exists. Here are some hints:
252
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000253* The authors strongly suggest getting a copy of the Tk man pages.
254 Specifically, the man pages in the ``manN`` directory are most useful.
255 The ``man3`` man pages describe the C interface to the Tk library and thus
256 are not especially helpful for script writers.
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
259 Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
260 the novice. The book is not exhaustive, and for many details it defers to the
261 man pages.
262
Georg Brandl48310cd2009-01-03 21:18:54 +0000263* :file:`tkinter/__init__.py` is a last resort for most, but can be a good
Georg Brandlac6060c2008-05-17 18:44:45 +0000264 place to go when nothing else makes sense.
Georg Brandl116aa622007-08-15 14:28:22 +0000265
266
Georg Brandl116aa622007-08-15 14:28:22 +0000267A Simple Hello World Program
268^^^^^^^^^^^^^^^^^^^^^^^^^^^^
269
Georg Brandl116aa622007-08-15 14:28:22 +0000270::
271
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700272 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700274 class Application(tk.Frame):
275 def __init__(self, master=None):
Berker Peksag3093bf12016-07-14 07:32:43 +0300276 super().__init__(master)
Daniel Lovella80af772018-10-30 07:56:07 -0700277 self.master = master
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700278 self.pack()
Berker Peksag3093bf12016-07-14 07:32:43 +0300279 self.create_widgets()
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Berker Peksag3093bf12016-07-14 07:32:43 +0300281 def create_widgets(self):
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700282 self.hi_there = tk.Button(self)
283 self.hi_there["text"] = "Hello World\n(click me)"
284 self.hi_there["command"] = self.say_hi
285 self.hi_there.pack(side="top")
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Berker Peksag3093bf12016-07-14 07:32:43 +0300287 self.quit = tk.Button(self, text="QUIT", fg="red",
Daniel Lovella80af772018-10-30 07:56:07 -0700288 command=self.master.destroy)
Berker Peksag3093bf12016-07-14 07:32:43 +0300289 self.quit.pack(side="bottom")
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700291 def say_hi(self):
292 print("hi there, everyone!")
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700294 root = tk.Tk()
295 app = Application(master=root)
296 app.mainloop()
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298
299A (Very) Quick Look at Tcl/Tk
300-----------------------------
301
302The class hierarchy looks complicated, but in actual practice, application
303programmers almost always refer to the classes at the very bottom of the
304hierarchy.
305
Georg Brandl116aa622007-08-15 14:28:22 +0000306Notes:
307
308* These classes are provided for the purposes of organizing certain functions
309 under one namespace. They aren't meant to be instantiated independently.
310
311* The :class:`Tk` class is meant to be instantiated only once in an application.
312 Application programmers need not instantiate one explicitly, the system creates
313 one whenever any of the other classes are instantiated.
314
315* The :class:`Widget` class is not meant to be instantiated, it is meant only
316 for subclassing to make "real" widgets (in C++, this is called an 'abstract
317 class').
318
319To make use of this reference material, there will be times when you will need
320to know how to read short passages of Tk and how to identify the various parts
321of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
Georg Brandlac6060c2008-05-17 18:44:45 +0000322:mod:`tkinter` equivalents of what's below.)
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
325of tokens separated by spaces. A Tk widget is just its *class*, the *options*
326that help configure it, and the *actions* that make it do useful things.
327
328To make a widget in Tk, the command is always of the form::
329
330 classCommand newPathname options
331
332*classCommand*
333 denotes which kind of widget to make (a button, a label, a menu...)
334
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200335.. index:: single: . (dot); in Tkinter
336
Georg Brandl116aa622007-08-15 14:28:22 +0000337*newPathname*
338 is the new name for this widget. All names in Tk must be unique. To help
339 enforce this, widgets in Tk are named with *pathnames*, just like files in a
340 file system. The top level widget, the *root*, is called ``.`` (period) and
341 children are delimited by more periods. For example,
342 ``.myApp.controlPanel.okButton`` might be the name of a widget.
343
344*options*
345 configure the widget's appearance and in some cases, its behavior. The options
346 come in the form of a list of flags and values. Flags are preceded by a '-',
347 like Unix shell command flags, and values are put in quotes if they are more
348 than one word.
349
350For example::
351
352 button .fred -fg red -text "hi there"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000353 ^ ^ \______________________/
Georg Brandl116aa622007-08-15 14:28:22 +0000354 | | |
355 class new options
356 command widget (-opt val -opt val ...)
357
358Once created, the pathname to the widget becomes a new command. This new
359*widget command* is the programmer's handle for getting the new widget to
360perform some *action*. In C, you'd express this as someAction(fred,
361someOptions), in C++, you would express this as fred.someAction(someOptions),
362and in Tk, you say::
363
Georg Brandl48310cd2009-01-03 21:18:54 +0000364 .fred someAction someOptions
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366Note that the object name, ``.fred``, starts with a dot.
367
368As you'd expect, the legal values for *someAction* will depend on the widget's
369class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
370does not work if fred is a label (disabling of labels is not supported in Tk).
371
372The legal values of *someOptions* is action dependent. Some actions, like
373``disable``, require no arguments, others, like a text-entry box's ``delete``
374command, would need arguments to specify what range of text to delete.
375
376
377.. _tkinter-basic-mapping:
378
379Mapping Basic Tk into Tkinter
380-----------------------------
381
382Class commands in Tk correspond to class constructors in Tkinter. ::
383
384 button .fred =====> fred = Button()
385
386The master of an object is implicit in the new name given to it at creation
387time. In Tkinter, masters are specified explicitly. ::
388
389 button .panel.fred =====> fred = Button(panel)
390
391The configuration options in Tk are given in lists of hyphened tags followed by
392values. In Tkinter, options are specified as keyword-arguments in the instance
393constructor, and keyword-args for configure calls or as instance indices, in
394dictionary style, for established instances. See section
395:ref:`tkinter-setting-options` on setting options. ::
396
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000397 button .fred -fg red =====> fred = Button(panel, fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000398 .fred configure -fg red =====> fred["fg"] = red
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000399 OR ==> fred.config(fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401In Tk, to perform an action on a widget, use the widget name as a command, and
402follow it with an action name, possibly with arguments (options). In Tkinter,
403you call methods on the class instance to invoke actions on the widget. The
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000404actions (methods) that a given widget can perform are listed in
405:file:`tkinter/__init__.py`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407 .fred invoke =====> fred.invoke()
408
409To give a widget to the packer (geometry manager), you call pack with optional
410arguments. In Tkinter, the Pack class holds all this functionality, and the
411various forms of the pack command are implemented as methods. All widgets in
Georg Brandlac6060c2008-05-17 18:44:45 +0000412:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
Georg Brandl48310cd2009-01-03 21:18:54 +0000413methods. See the :mod:`tkinter.tix` module documentation for additional
Georg Brandlac6060c2008-05-17 18:44:45 +0000414information on the Form geometry manager. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000416 pack .fred -side left =====> fred.pack(side="left")
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418
419How Tk and Tkinter are Related
420------------------------------
421
Georg Brandl116aa622007-08-15 14:28:22 +0000422From the top down:
423
424Your App Here (Python)
Georg Brandlac6060c2008-05-17 18:44:45 +0000425 A Python application makes a :mod:`tkinter` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Georg Brandlac6060c2008-05-17 18:44:45 +0000427tkinter (Python Package)
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000428 This call (say, for example, creating a button widget), is implemented in
429 the :mod:`tkinter` package, which is written in Python. This Python
430 function will parse the commands and the arguments and convert them into a
431 form that makes them look as if they had come from a Tk script instead of
432 a Python script.
Georg Brandl116aa622007-08-15 14:28:22 +0000433
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000434_tkinter (C)
Georg Brandl116aa622007-08-15 14:28:22 +0000435 These commands and their arguments will be passed to a C function in the
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000436 :mod:`_tkinter` - note the underscore - extension module.
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438Tk Widgets (C and Tcl)
439 This C function is able to make calls into other C modules, including the C
440 functions that make up the Tk library. Tk is implemented in C and some Tcl.
441 The Tcl part of the Tk widgets is used to bind certain default behaviors to
Georg Brandlac6060c2008-05-17 18:44:45 +0000442 widgets, and is executed once at the point where the Python :mod:`tkinter`
443 package is imported. (The user never sees this stage).
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445Tk (C)
446 The Tk part of the Tk Widgets implement the final mapping to ...
447
448Xlib (C)
449 the Xlib library to draw graphics on the screen.
450
451
Miss Islington (bot)2666d702021-08-11 10:16:10 -0700452Threading model
453---------------
454
455Python and Tcl/Tk have very different threading models, which :mod:`tkinter`
456tries to bridge. If you use threads, you may need to be aware of this.
457
458A Python interpreter may have many threads associated with it. In Tcl, multiple
459threads can be created, but each thread has a separate Tcl interpreter instance
460associated with it. Threads can also create more than one interpreter instance,
461though each interpreter instance can be used only by the one thread that created it.
462
463Each :class:`Tk` object created by :mod:`tkinter` contains a Tcl interpreter.
464It also keeps track of which thread created that interpreter. Calls to
465:mod:`tkinter` can be made from any Python thread. Internally, if a call comes
466from a thread other than the one that created the :class:`Tk` object, an event
467is posted to the interpreter's event queue, and when executed, the result is
468returned to the calling Python thread.
469
470Tcl/Tk applications are normally event-driven, meaning that after initialization,
471the interpreter runs an event loop (i.e. :func:`Tk.mainloop`) and responds to events.
472Because it is single-threaded, event handlers must respond quickly, otherwise they
473will block other events from being processed. To avoid this, any long-running
474computations should not run in an event handler, but are either broken into smaller
475pieces using timers, or run in another thread. This is different from many GUI
476toolkits where the GUI runs in a completely separate thread from all application
477code including event handlers.
478
479If the Tcl interpreter is not running the event loop and processing events, any
480:mod:`tkinter` calls made from threads other than the one running the Tcl
481interpreter will fail.
482
483A number of special cases exist:
484
485 * Tcl/Tk libraries can be built so they are not thread-aware. In this case,
486 :mod:`tkinter` calls the library from the originating Python thread, even
487 if this is different than the thread that created the Tcl interpreter. A global
488 lock ensures only one call occurs at a time.
489
490 * While :mod:`tkinter` allows you to create more than one instance of a :class:`Tk`
491 object (with its own interpreter), all interpreters that are part of the same
492 thread share a common event queue, which gets ugly fast. In practice, don't create
493 more than one instance of :class:`Tk` at a time. Otherwise, it's best to create
494 them in separate threads and ensure you're running a thread-aware Tcl/Tk build.
495
496 * Blocking event handlers are not the only way to prevent the Tcl interpreter from
497 reentering the event loop. It is even possible to run multiple nested event loops
498 or abandon the event loop entirely. If you're doing anything tricky when it comes
499 to events or threads, be aware of these possibilities.
500
501 * There are a few select :mod:`tkinter` functions that presently work only when
502 called from the thread that created the Tcl interpreter.
503
504
Georg Brandl116aa622007-08-15 14:28:22 +0000505Handy Reference
506---------------
507
508
509.. _tkinter-setting-options:
510
511Setting Options
512^^^^^^^^^^^^^^^
513
514Options control things like the color and border width of a widget. Options can
515be set in three ways:
516
517At object creation time, using keyword arguments
518 ::
519
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000520 fred = Button(self, fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522After object creation, treating the option name like a dictionary index
523 ::
524
525 fred["fg"] = "red"
526 fred["bg"] = "blue"
527
528Use the config() method to update multiple attrs subsequent to object creation
529 ::
530
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000531 fred.config(fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533For a complete explanation of a given option and its behavior, see the Tk man
534pages for the widget in question.
535
536Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
537for each widget. The former is a list of options that are common to many
538widgets, the latter are the options that are idiosyncratic to that particular
539widget. The Standard Options are documented on the :manpage:`options(3)` man
540page.
541
542No distinction between standard and widget-specific options is made in this
543document. Some options don't apply to some kinds of widgets. Whether a given
544widget responds to a particular option depends on the class of the widget;
545buttons have a ``command`` option, labels do not.
546
547The options supported by a given widget are listed in that widget's man page, or
548can be queried at runtime by calling the :meth:`config` method without
549arguments, or by calling the :meth:`keys` method on that widget. The return
550value of these calls is a dictionary whose key is the name of the option as a
551string (for example, ``'relief'``) and whose values are 5-tuples.
552
553Some options, like ``bg`` are synonyms for common options with long names
554(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
555of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
556back will contain the name of the synonym and the "real" option (such as
557``('bg', 'background')``).
558
559+-------+---------------------------------+--------------+
560| Index | Meaning | Example |
561+=======+=================================+==============+
562| 0 | option name | ``'relief'`` |
563+-------+---------------------------------+--------------+
564| 1 | option name for database lookup | ``'relief'`` |
565+-------+---------------------------------+--------------+
566| 2 | option class for database | ``'Relief'`` |
567| | lookup | |
568+-------+---------------------------------+--------------+
569| 3 | default value | ``'raised'`` |
570+-------+---------------------------------+--------------+
571| 4 | current value | ``'groove'`` |
572+-------+---------------------------------+--------------+
573
574Example::
575
Collin Winterc79461b2007-09-01 23:34:30 +0000576 >>> print(fred.config())
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200577 {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}
Georg Brandl116aa622007-08-15 14:28:22 +0000578
579Of course, the dictionary printed will include all the options available and
580their values. This is meant only as an example.
581
582
583The Packer
584^^^^^^^^^^
585
586.. index:: single: packing (widgets)
587
Georg Brandl116aa622007-08-15 14:28:22 +0000588The packer is one of Tk's geometry-management mechanisms. Geometry managers
Nathan Mecaf9492020-08-02 22:13:03 -0400589are used to specify the relative positioning of widgets within their container -
590their mutual *master*. In contrast to the more cumbersome *placer* (which is
591used less commonly, and we do not cover here), the packer takes qualitative
592relationship specification - *above*, *to the left of*, *filling*, etc - and
593works everything out to determine the exact placement coordinates for you.
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Georg Brandl116aa622007-08-15 14:28:22 +0000595The size of any *master* widget is determined by the size of the "slave widgets"
596inside. The packer is used to control where slave widgets appear inside the
597master into which they are packed. You can pack widgets into frames, and frames
598into other frames, in order to achieve the kind of layout you desire.
599Additionally, the arrangement is dynamically adjusted to accommodate incremental
600changes to the configuration, once it is packed.
601
602Note that widgets do not appear until they have had their geometry specified
603with a geometry manager. It's a common early mistake to leave out the geometry
604specification, and then be surprised when the widget is created but nothing
605appears. A widget will appear only after it has had, for example, the packer's
606:meth:`pack` method applied to it.
607
608The pack() method can be called with keyword-option/value pairs that control
609where the widget is to appear within its container, and how it is to behave when
610the main application window is resized. Here are some examples::
611
612 fred.pack() # defaults to side = "top"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000613 fred.pack(side="left")
614 fred.pack(expand=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000615
616
617Packer Options
618^^^^^^^^^^^^^^
619
620For more extensive information on the packer and the options that it can take,
621see the man pages and page 183 of John Ousterhout's book.
622
Georg Brandl48310cd2009-01-03 21:18:54 +0000623anchor
Georg Brandl116aa622007-08-15 14:28:22 +0000624 Anchor type. Denotes where the packer is to place each slave in its parcel.
625
626expand
627 Boolean, ``0`` or ``1``.
628
629fill
630 Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
631
632ipadx and ipady
633 A distance - designating internal padding on each side of the slave widget.
634
635padx and pady
636 A distance - designating external padding on each side of the slave widget.
637
638side
639 Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
640
641
642Coupling Widget Variables
643^^^^^^^^^^^^^^^^^^^^^^^^^
644
645The current-value setting of some widgets (like text entry widgets) can be
646connected directly to application variables by using special options. These
647options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
648``value``. This connection works both ways: if the variable changes for any
649reason, the widget it's connected to will be updated to reflect the new value.
650
Georg Brandlac6060c2008-05-17 18:44:45 +0000651Unfortunately, in the current implementation of :mod:`tkinter` it is not
Georg Brandl116aa622007-08-15 14:28:22 +0000652possible to hand over an arbitrary Python variable to a widget through a
653``variable`` or ``textvariable`` option. The only kinds of variables for which
654this works are variables that are subclassed from a class called Variable,
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000655defined in :mod:`tkinter`.
Georg Brandl116aa622007-08-15 14:28:22 +0000656
657There are many useful subclasses of Variable already defined:
658:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
659:class:`BooleanVar`. To read the current value of such a variable, call the
Georg Brandl502d9a52009-07-26 15:02:41 +0000660:meth:`get` method on it, and to change its value you call the :meth:`!set`
Georg Brandl116aa622007-08-15 14:28:22 +0000661method. If you follow this protocol, the widget will always track the value of
662the variable, with no further intervention on your part.
663
664For example::
665
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100666 import tkinter as tk
667
668 class App(tk.Frame):
669 def __init__(self, master):
Berker Peksag3093bf12016-07-14 07:32:43 +0300670 super().__init__(master)
Georg Brandl116aa622007-08-15 14:28:22 +0000671 self.pack()
672
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100673 self.entrythingy = tk.Entry()
Georg Brandl116aa622007-08-15 14:28:22 +0000674 self.entrythingy.pack()
675
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100676 # Create the application variable.
677 self.contents = tk.StringVar()
678 # Set it to some value.
Georg Brandl116aa622007-08-15 14:28:22 +0000679 self.contents.set("this is a variable")
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100680 # Tell the entry widget to watch this variable.
Georg Brandl116aa622007-08-15 14:28:22 +0000681 self.entrythingy["textvariable"] = self.contents
682
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100683 # Define a callback for when the user hits return.
684 # It prints the current value of the variable.
Georg Brandl116aa622007-08-15 14:28:22 +0000685 self.entrythingy.bind('<Key-Return>',
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100686 self.print_contents)
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688 def print_contents(self, event):
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100689 print("Hi. The current entry content is:",
Collin Winterc79461b2007-09-01 23:34:30 +0000690 self.contents.get())
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100692 root = tk.Tk()
693 myapp = App(root)
694 myapp.mainloop()
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696The Window Manager
697^^^^^^^^^^^^^^^^^^
698
699.. index:: single: window manager (widgets)
700
Georg Brandl116aa622007-08-15 14:28:22 +0000701In Tk, there is a utility command, ``wm``, for interacting with the window
702manager. Options to the ``wm`` command allow you to control things like titles,
Georg Brandlac6060c2008-05-17 18:44:45 +0000703placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
Georg Brandl116aa622007-08-15 14:28:22 +0000704been implemented as methods on the :class:`Wm` class. Toplevel widgets are
705subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
706directly.
707
708To get at the toplevel window that contains a given widget, you can often just
709refer to the widget's master. Of course if the widget has been packed inside of
710a frame, the master won't represent a toplevel window. To get at the toplevel
711window that contains an arbitrary widget, you can call the :meth:`_root` method.
712This method begins with an underscore to denote the fact that this function is
713part of the implementation, and not an interface to Tk functionality.
714
Georg Brandl116aa622007-08-15 14:28:22 +0000715Here are some examples of typical usage::
716
Berker Peksag3093bf12016-07-14 07:32:43 +0300717 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Berker Peksag3093bf12016-07-14 07:32:43 +0300719 class App(tk.Frame):
720 def __init__(self, master=None):
721 super().__init__(master)
722 self.pack()
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724 # create the application
725 myapp = App()
726
727 #
728 # here are method calls to the window manager class
729 #
730 myapp.master.title("My Do-Nothing Application")
731 myapp.master.maxsize(1000, 400)
732
733 # start the program
734 myapp.mainloop()
735
736
737Tk Option Data Types
738^^^^^^^^^^^^^^^^^^^^
739
740.. index:: single: Tk Option Data Types
741
Georg Brandl116aa622007-08-15 14:28:22 +0000742anchor
743 Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
744 ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
745
746bitmap
747 There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
748 ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
749 ``'warning'``. To specify an X bitmap filename, give the full path to the file,
750 preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
751
752boolean
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +0200753 You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000754
755callback
756 This is any Python function that takes no arguments. For example::
757
758 def print_it():
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000759 print("hi there")
Georg Brandl116aa622007-08-15 14:28:22 +0000760 fred["command"] = print_it
761
762color
763 Colors can be given as the names of X colors in the rgb.txt file, or as strings
764 representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
765 ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
766 represent any legal hex digit. See page 160 of Ousterhout's book for details.
767
768cursor
769 The standard X cursor names from :file:`cursorfont.h` can be used, without the
770 ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
771 string ``"hand2"``. You can also specify a bitmap and mask file of your own.
772 See page 179 of Ousterhout's book.
773
774distance
775 Screen distances can be specified in either pixels or absolute distances.
776 Pixels are given as numbers and absolute distances as strings, with the trailing
777 character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
778 millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
779 as ``"3.5i"``.
780
781font
782 Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
783 positive numbers are measured in points; sizes with negative numbers are
784 measured in pixels.
785
786geometry
787 This is a string of the form ``widthxheight``, where width and height are
788 measured in pixels for most widgets (in characters for widgets displaying text).
789 For example: ``fred["geometry"] = "200x100"``.
790
791justify
792 Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
793 ``"fill"``.
794
795region
796 This is a string with four space-delimited elements, each of which is a legal
797 distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
798 ``"3c 2c 4c 10.43c"`` are all legal regions.
799
800relief
801 Determines what the border style of a widget will be. Legal values are:
802 ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
803
804scrollcommand
Georg Brandl502d9a52009-07-26 15:02:41 +0000805 This is almost always the :meth:`!set` method of some scrollbar widget, but can
Georg Brandl59b44722010-12-30 22:12:40 +0000806 be any widget method that takes a single argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000807
Nikhil80428ed2019-09-10 01:55:34 -0700808wrap
Georg Brandl116aa622007-08-15 14:28:22 +0000809 Must be one of: ``"none"``, ``"char"``, or ``"word"``.
810
Nikhil80428ed2019-09-10 01:55:34 -0700811.. _Bindings-and-Events:
Georg Brandl116aa622007-08-15 14:28:22 +0000812
813Bindings and Events
814^^^^^^^^^^^^^^^^^^^
815
816.. index::
817 single: bind (widgets)
818 single: events (widgets)
819
Georg Brandl116aa622007-08-15 14:28:22 +0000820The bind method from the widget command allows you to watch for certain events
821and to have a callback function trigger when that event type occurs. The form
822of the bind method is::
823
824 def bind(self, sequence, func, add=''):
825
826where:
827
828sequence
829 is a string that denotes the target kind of event. (See the bind man page and
830 page 201 of John Ousterhout's book for details).
831
832func
833 is a Python function, taking one argument, to be invoked when the event occurs.
834 An Event instance will be passed as the argument. (Functions deployed this way
835 are commonly known as *callbacks*.)
836
837add
838 is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
839 this binding is to replace any other bindings that this event is associated
840 with. Passing a ``'+'`` means that this function is to be added to the list
841 of functions bound to this event type.
842
843For example::
844
Berker Peksag3093bf12016-07-14 07:32:43 +0300845 def turn_red(self, event):
Georg Brandl116aa622007-08-15 14:28:22 +0000846 event.widget["activeforeground"] = "red"
847
Berker Peksag3093bf12016-07-14 07:32:43 +0300848 self.button.bind("<Enter>", self.turn_red)
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850Notice how the widget field of the event is being accessed in the
Berker Peksag3093bf12016-07-14 07:32:43 +0300851``turn_red()`` callback. This field contains the widget that caught the X
Georg Brandl116aa622007-08-15 14:28:22 +0000852event. The following table lists the other event fields you can access, and how
853they are denoted in Tk, which can be useful when referring to the Tk man pages.
Georg Brandl116aa622007-08-15 14:28:22 +0000854
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000855+----+---------------------+----+---------------------+
856| Tk | Tkinter Event Field | Tk | Tkinter Event Field |
857+====+=====================+====+=====================+
858| %f | focus | %A | char |
859+----+---------------------+----+---------------------+
860| %h | height | %E | send_event |
861+----+---------------------+----+---------------------+
862| %k | keycode | %K | keysym |
863+----+---------------------+----+---------------------+
864| %s | state | %N | keysym_num |
865+----+---------------------+----+---------------------+
866| %t | time | %T | type |
867+----+---------------------+----+---------------------+
868| %w | width | %W | widget |
869+----+---------------------+----+---------------------+
870| %x | x | %X | x_root |
871+----+---------------------+----+---------------------+
872| %y | y | %Y | y_root |
873+----+---------------------+----+---------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000874
875
876The index Parameter
877^^^^^^^^^^^^^^^^^^^
878
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000879A number of widgets require "index" parameters to be passed. These are used to
Georg Brandl116aa622007-08-15 14:28:22 +0000880point at a specific place in a Text widget, or to particular characters in an
881Entry widget, or to particular menu items in a Menu widget.
882
Georg Brandl116aa622007-08-15 14:28:22 +0000883Entry widget indexes (index, view index, etc.)
884 Entry widgets have options that refer to character positions in the text being
Georg Brandlac6060c2008-05-17 18:44:45 +0000885 displayed. You can use these :mod:`tkinter` functions to access these special
Georg Brandl116aa622007-08-15 14:28:22 +0000886 points in text widgets:
887
Georg Brandl116aa622007-08-15 14:28:22 +0000888Text widget indexes
889 The index notation for Text widgets is very rich and is best described in the Tk
890 man pages.
891
892Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
893 Some options and methods for menus manipulate specific menu entries. Anytime a
894 menu index is needed for an option or a parameter, you may pass in:
895
896 * an integer which refers to the numeric position of the entry in the widget,
897 counted from the top, starting with 0;
898
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000899 * the string ``"active"``, which refers to the menu position that is currently
Georg Brandl116aa622007-08-15 14:28:22 +0000900 under the cursor;
901
902 * the string ``"last"`` which refers to the last menu item;
903
904 * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
905 as a y pixel coordinate in the menu's coordinate system;
906
907 * the string ``"none"``, which indicates no menu entry at all, most often used
908 with menu.activate() to deactivate all entries, and finally,
909
910 * a text string that is pattern matched against the label of the menu entry, as
911 scanned from the top of the menu to the bottom. Note that this index type is
912 considered after all the others, which means that matches for menu items
913 labelled ``last``, ``active``, or ``none`` may be interpreted as the above
914 literals, instead.
915
916
917Images
918^^^^^^
919
Andrés Delfino4b685bf2018-04-17 02:34:35 -0300920Images of different formats can be created through the corresponding subclass
921of :class:`tkinter.Image`:
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Andrés Delfino4b685bf2018-04-17 02:34:35 -0300923* :class:`BitmapImage` for images in XBM format.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
Andrés Delfino4b685bf2018-04-17 02:34:35 -0300925* :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter
926 is supported starting with Tk 8.6.
Georg Brandl116aa622007-08-15 14:28:22 +0000927
928Either type of image is created through either the ``file`` or the ``data``
929option (other options are available as well).
930
931The image object can then be used wherever an ``image`` option is supported by
932some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
933reference to the image. When the last Python reference to the image object is
934deleted, the image data is deleted as well, and Tk will display an empty box
935wherever the image was used.
Terry Jan Reedyd9865632015-05-17 14:49:26 -0400936
Andrés Delfinob81ca282018-04-21 09:17:26 -0300937.. seealso::
938
939 The `Pillow <http://python-pillow.org/>`_ package adds support for
940 formats such as BMP, JPEG, TIFF, and WebP, among others.
Terry Jan Reedyd9865632015-05-17 14:49:26 -0400941
942.. _tkinter-file-handlers:
943
944File Handlers
945-------------
946
947Tk allows you to register and unregister a callback function which will be
948called from the Tk mainloop when I/O is possible on a file descriptor.
949Only one handler may be registered per file descriptor. Example code::
950
951 import tkinter
952 widget = tkinter.Tk()
953 mask = tkinter.READABLE | tkinter.WRITABLE
954 widget.tk.createfilehandler(file, mask, callback)
955 ...
956 widget.tk.deletefilehandler(file)
957
958This feature is not available on Windows.
959
960Since you don't know how many bytes are available for reading, you may not
961want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
962:meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods,
963since these will insist on reading a predefined number of bytes.
964For sockets, the :meth:`~socket.socket.recv` or
965:meth:`~socket.socket.recvfrom` methods will work fine; for other files,
966use raw reads or ``os.read(file.fileno(), maxbytecount)``.
967
968
969.. method:: Widget.tk.createfilehandler(file, mask, func)
970
971 Registers the file handler callback function *func*. The *file* argument
972 may either be an object with a :meth:`~io.IOBase.fileno` method (such as
973 a file or socket object), or an integer file descriptor. The *mask*
974 argument is an ORed combination of any of the three constants below.
975 The callback is called as follows::
976
977 callback(file, mask)
978
979
980.. method:: Widget.tk.deletefilehandler(file)
981
982 Unregisters a file handler.
983
984
985.. data:: READABLE
986 WRITABLE
987 EXCEPTION
988
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100989 Constants used in the *mask* arguments.