blob: 7483ccd6f40e1d39dceac921025a7a1e2f8061d6 [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
14the Tk GUI toolkit. Both Tk and :mod:`tkinter` are available on most Unix
Georg Brandlc575c902008-09-13 17:46:05 +000015platforms, as well as on Windows systems. (Tk itself is not part of Python; it
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030016is maintained at ActiveState.)
17
18Running ``python -m tkinter`` from the command line should open a window
19demonstrating a simple Tk interface, letting you know that :mod:`tkinter` is
20properly installed on your system, and also showing what version of Tcl/Tk is
21installed, so you can read the Tcl/Tk documentation specific to that version.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Miss Islington (bot)2666d702021-08-11 10:16:10 -070023Tkinter supports a range of Tcl/Tk versions, built either with or
24without thread support. The official Python binary release bundles Tcl/Tk 8.6
25threaded. See the source code for the :mod:`_tkinter` module
26for more information about supported versions.
27
28Tkinter is not a thin wrapper, but adds a fair amount of its own logic to
29make the experience more pythonic. This documentation will concentrate on these
30additions and changes, and refer to the official Tcl/Tk documentation for
31details that are unchanged.
32
Georg Brandl116aa622007-08-15 14:28:22 +000033.. seealso::
34
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030035 Tkinter documentation:
36
Zachary Ware08863992014-03-18 09:19:18 -050037 `Python Tkinter Resources <https://wiki.python.org/moin/TkInter>`_
Georg Brandl116aa622007-08-15 14:28:22 +000038 The Python Tkinter Topic Guide provides a great deal of information on using Tk
39 from Python and links to other sources of information on Tk.
40
Andrew Svetlove708a8a2012-07-26 17:02:57 +030041 `TKDocs <http://www.tkdocs.com/>`_
42 Extensive tutorial plus friendlier widget pages for some of the widgets.
43
Mark Roseman06d0b8b2020-09-10 13:04:20 -070044 `Tkinter 8.5 reference: a GUI for Python <https://www.tkdocs.com/shipman/>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030045 On-line reference material.
46
47 `Tkinter docs from effbot <http://effbot.org/tkinterbook/>`_
48 Online reference for tkinter supported by effbot.org.
49
Sanyam Khurana338cd832018-01-20 05:55:37 +053050 `Programming Python <http://learning-python.com/about-pp4e.html>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030051 Book by Mark Lutz, has excellent coverage of Tkinter.
52
Sanyam Khurana1b4587a2017-12-06 22:09:33 +053053 `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 -040054 Book by Mark Roseman about building attractive and modern graphical user interfaces with Python and Tkinter.
Andrew Svetlove708a8a2012-07-26 17:02:57 +030055
Georg Brandl5d941342016-02-26 19:37:12 +010056 `Python and Tkinter Programming <https://www.manning.com/books/python-and-tkinter-programming>`_
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030057 Book by John Grayson (ISBN 1-884777-81-3).
58
59 Tcl/Tk documentation:
60
61 `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
62 Most commands are available as :mod:`tkinter` or :mod:`tkinter.ttk` classes.
63 Change '8.6' to match the version of your Tcl/Tk installation.
64
65 `Tcl/Tk recent man pages <https://www.tcl.tk/doc/>`_
66 Recent Tcl/Tk manuals on www.tcl.tk.
67
Julien Palard7114c652019-05-25 20:02:24 +020068 `ActiveState Tcl Home Page <https://tcl.tk>`_
Andrés Delfino67a8f4f2018-04-25 14:53:58 -030069 The Tk/Tcl development is largely taking place at ActiveState.
70
71 `Tcl and the Tk Toolkit <https://www.amazon.com/exec/obidos/ASIN/020163337X>`_
72 Book by John Ousterhout, the inventor of Tcl.
73
74 `Practical Programming in Tcl and Tk <http://www.beedub.com/book/>`_
75 Brent Welch's encyclopedic book.
Georg Brandl116aa622007-08-15 14:28:22 +000076
77
Miss Islington (bot)2666d702021-08-11 10:16:10 -070078Architecture
79------------
80
81Tcl/Tk is not a single library but rather consists of a few distinct
82modules, each with a separate functionality and its own official
83documentation. Python's binary releases also ship an add-on module
84together with it.
85
86Tcl
87 Tcl is a dynamic interpreted programming language, just like Python. Though
88 it can be used on its own as a general-purpose programming language, it is
89 most commonly embedded into C applications as a scripting engine or an
90 interface to the Tk toolkit. The Tcl library has a C interface to
91 create and manage one or more instances of a Tcl interpreter, run Tcl
92 commands and scripts in those instances, and add custom commands
93 implemented in either Tcl or C. Each interpreter has an event queue,
94 and there are facilities to send events to it and process them.
95 Unlike Python, Tcl's execution model is designed around cooperative
96 multitasking, and Tkinter bridges this difference
97 (see `Threading model`_ for details).
98
99Tk
100 Tk is a `Tcl package <http://wiki.tcl.tk/37432>`_ implemented in C
101 that adds custom commands to create and manipulate GUI widgets. Each
102 :class:`Tk` object embeds its own Tcl interpreter instance with Tk loaded into
103 it. Tk's widgets are very customizable, though at the cost of a dated appearance.
104 Tk uses Tcl's event queue to generate and process GUI events.
105
106Ttk
107 Themed Tk (Ttk) is a newer family of Tk widgets that provide a much better
108 appearance on different platforms than many of the classic Tk widgets.
109 Ttk is distributed as part of Tk, starting with Tk version 8.5. Python
110 bindings are provided in a separate module, :mod:`tkinter.ttk`.
111
112Tix
113 `Tix <https://core.tcl.tk/jenglish/gutter/packages/tix.html>`_ is an older
114 third-party Tcl package, an add-on for Tk that adds several new widgets.
115 Python bindings are found in the :mod:`tkinter.tix` module.
116 It's deprecated in favor of Ttk.
117
118
Georg Brandl116aa622007-08-15 14:28:22 +0000119Tkinter Modules
120---------------
121
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000122Most of the time, :mod:`tkinter` is all you really need, but a number of
123additional modules are available as well. The Tk interface is located in a
Georg Brandl116aa622007-08-15 14:28:22 +0000124binary module named :mod:`_tkinter`. This module contains the low-level
125interface to Tk, and should never be used directly by application programmers.
126It is usually a shared library (or DLL), but might in some cases be statically
127linked with the Python interpreter.
128
Georg Brandlac6060c2008-05-17 18:44:45 +0000129In addition to the Tk interface module, :mod:`tkinter` includes a number of
Georg Brandl48310cd2009-01-03 21:18:54 +0000130Python modules, :mod:`tkinter.constants` being one of the most important.
Georg Brandlac6060c2008-05-17 18:44:45 +0000131Importing :mod:`tkinter` will automatically import :mod:`tkinter.constants`,
132so, usually, to use Tkinter all you need is a simple import statement::
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Georg Brandlac6060c2008-05-17 18:44:45 +0000134 import tkinter
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136Or, more often::
137
Georg Brandlac6060c2008-05-17 18:44:45 +0000138 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140
141.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
142
143 The :class:`Tk` class is instantiated without arguments. This creates a toplevel
144 widget of Tk which usually is the main window of an application. Each instance
145 has its own associated Tcl interpreter.
146
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000147 .. FIXME: The following keyword arguments are currently recognized:
Georg Brandl116aa622007-08-15 14:28:22 +0000148
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
151
152 The :func:`Tcl` function is a factory function which creates an object much like
153 that created by the :class:`Tk` class, except that it does not initialize the Tk
154 subsystem. This is most often useful when driving the Tcl interpreter in an
155 environment where one doesn't want to create extraneous toplevel windows, or
156 where one cannot (such as Unix/Linux systems without an X server). An object
157 created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
158 subsystem initialized) by calling its :meth:`loadtk` method.
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161Other modules that provide Tk support include:
162
Georg Brandlac6060c2008-05-17 18:44:45 +0000163:mod:`tkinter.colorchooser`
Georg Brandl116aa622007-08-15 14:28:22 +0000164 Dialog to let the user choose a color.
165
Georg Brandlac6060c2008-05-17 18:44:45 +0000166:mod:`tkinter.commondialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000167 Base class for the dialogs defined in the other modules listed here.
168
Georg Brandlac6060c2008-05-17 18:44:45 +0000169:mod:`tkinter.filedialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000170 Common dialogs to allow the user to specify a file to open or save.
171
Georg Brandlac6060c2008-05-17 18:44:45 +0000172:mod:`tkinter.font`
Georg Brandl116aa622007-08-15 14:28:22 +0000173 Utilities to help work with fonts.
174
Georg Brandlac6060c2008-05-17 18:44:45 +0000175:mod:`tkinter.messagebox`
Georg Brandl116aa622007-08-15 14:28:22 +0000176 Access to standard Tk dialog boxes.
177
Nikhil80428ed2019-09-10 01:55:34 -0700178:mod:`tkinter.scrolledtext`
179 Text widget with a vertical scroll bar built in.
180
Georg Brandlac6060c2008-05-17 18:44:45 +0000181:mod:`tkinter.simpledialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000182 Basic dialogs and convenience functions.
183
Georg Brandlac6060c2008-05-17 18:44:45 +0000184:mod:`tkinter.dnd`
Georg Brandl48310cd2009-01-03 21:18:54 +0000185 Drag-and-drop support for :mod:`tkinter`. This is experimental and should
Georg Brandlac6060c2008-05-17 18:44:45 +0000186 become deprecated when it is replaced with the Tk DND.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl23d11d32008-09-21 07:50:52 +0000188:mod:`turtle`
Georg Brandl116aa622007-08-15 14:28:22 +0000189 Turtle graphics in a Tk window.
190
191
192Tkinter Life Preserver
193----------------------
194
195.. sectionauthor:: Matt Conway
196
197
198This section is not designed to be an exhaustive tutorial on either Tk or
199Tkinter. Rather, it is intended as a stop gap, providing some introductory
200orientation on the system.
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202Credits:
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204* Tk was written by John Ousterhout while at Berkeley.
205
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000206* Tkinter was written by Steen Lumholt and Guido van Rossum.
207
Georg Brandl116aa622007-08-15 14:28:22 +0000208* This Life Preserver was written by Matt Conway at the University of Virginia.
209
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000210* The HTML rendering, and some liberal editing, was produced from a FrameMaker
Georg Brandl116aa622007-08-15 14:28:22 +0000211 version by Ken Manheimer.
212
213* Fredrik Lundh elaborated and revised the class interface descriptions, to get
214 them current with Tk 4.2.
215
216* Mike Clarkson converted the documentation to LaTeX, and compiled the User
217 Interface chapter of the reference manual.
218
219
220How To Use This Section
221^^^^^^^^^^^^^^^^^^^^^^^
222
223This section is designed in two parts: the first half (roughly) covers
224background material, while the second half can be taken to the keyboard as a
225handy reference.
226
227When trying to answer questions of the form "how do I do blah", it is often best
Julien Palardae342cf2017-12-05 06:05:33 +0100228to find out how to do "blah" in straight Tk, and then convert this back into the
Georg Brandlac6060c2008-05-17 18:44:45 +0000229corresponding :mod:`tkinter` call. Python programmers can often guess at the
Georg Brandl116aa622007-08-15 14:28:22 +0000230correct Python command by looking at the Tk documentation. This means that in
231order to use Tkinter, you will have to know a little bit about Tk. This document
232can't fulfill that role, so the best we can do is point you to the best
233documentation that exists. Here are some hints:
234
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000235* The authors strongly suggest getting a copy of the Tk man pages.
236 Specifically, the man pages in the ``manN`` directory are most useful.
237 The ``man3`` man pages describe the C interface to the Tk library and thus
238 are not especially helpful for script writers.
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
241 Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
242 the novice. The book is not exhaustive, and for many details it defers to the
243 man pages.
244
Georg Brandl48310cd2009-01-03 21:18:54 +0000245* :file:`tkinter/__init__.py` is a last resort for most, but can be a good
Georg Brandlac6060c2008-05-17 18:44:45 +0000246 place to go when nothing else makes sense.
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248
Georg Brandl116aa622007-08-15 14:28:22 +0000249A Simple Hello World Program
250^^^^^^^^^^^^^^^^^^^^^^^^^^^^
251
Georg Brandl116aa622007-08-15 14:28:22 +0000252::
253
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700254 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700256 class Application(tk.Frame):
257 def __init__(self, master=None):
Berker Peksag3093bf12016-07-14 07:32:43 +0300258 super().__init__(master)
Daniel Lovella80af772018-10-30 07:56:07 -0700259 self.master = master
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700260 self.pack()
Berker Peksag3093bf12016-07-14 07:32:43 +0300261 self.create_widgets()
Georg Brandl116aa622007-08-15 14:28:22 +0000262
Berker Peksag3093bf12016-07-14 07:32:43 +0300263 def create_widgets(self):
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700264 self.hi_there = tk.Button(self)
265 self.hi_there["text"] = "Hello World\n(click me)"
266 self.hi_there["command"] = self.say_hi
267 self.hi_there.pack(side="top")
Georg Brandl116aa622007-08-15 14:28:22 +0000268
Berker Peksag3093bf12016-07-14 07:32:43 +0300269 self.quit = tk.Button(self, text="QUIT", fg="red",
Daniel Lovella80af772018-10-30 07:56:07 -0700270 command=self.master.destroy)
Berker Peksag3093bf12016-07-14 07:32:43 +0300271 self.quit.pack(side="bottom")
Georg Brandl116aa622007-08-15 14:28:22 +0000272
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700273 def say_hi(self):
274 print("hi there, everyone!")
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700276 root = tk.Tk()
277 app = Application(master=root)
278 app.mainloop()
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280
281A (Very) Quick Look at Tcl/Tk
282-----------------------------
283
284The class hierarchy looks complicated, but in actual practice, application
285programmers almost always refer to the classes at the very bottom of the
286hierarchy.
287
Georg Brandl116aa622007-08-15 14:28:22 +0000288Notes:
289
290* These classes are provided for the purposes of organizing certain functions
291 under one namespace. They aren't meant to be instantiated independently.
292
293* The :class:`Tk` class is meant to be instantiated only once in an application.
294 Application programmers need not instantiate one explicitly, the system creates
295 one whenever any of the other classes are instantiated.
296
297* The :class:`Widget` class is not meant to be instantiated, it is meant only
298 for subclassing to make "real" widgets (in C++, this is called an 'abstract
299 class').
300
301To make use of this reference material, there will be times when you will need
302to know how to read short passages of Tk and how to identify the various parts
303of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
Georg Brandlac6060c2008-05-17 18:44:45 +0000304:mod:`tkinter` equivalents of what's below.)
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
307of tokens separated by spaces. A Tk widget is just its *class*, the *options*
308that help configure it, and the *actions* that make it do useful things.
309
310To make a widget in Tk, the command is always of the form::
311
312 classCommand newPathname options
313
314*classCommand*
315 denotes which kind of widget to make (a button, a label, a menu...)
316
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200317.. index:: single: . (dot); in Tkinter
318
Georg Brandl116aa622007-08-15 14:28:22 +0000319*newPathname*
320 is the new name for this widget. All names in Tk must be unique. To help
321 enforce this, widgets in Tk are named with *pathnames*, just like files in a
322 file system. The top level widget, the *root*, is called ``.`` (period) and
323 children are delimited by more periods. For example,
324 ``.myApp.controlPanel.okButton`` might be the name of a widget.
325
326*options*
327 configure the widget's appearance and in some cases, its behavior. The options
328 come in the form of a list of flags and values. Flags are preceded by a '-',
329 like Unix shell command flags, and values are put in quotes if they are more
330 than one word.
331
332For example::
333
334 button .fred -fg red -text "hi there"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000335 ^ ^ \______________________/
Georg Brandl116aa622007-08-15 14:28:22 +0000336 | | |
337 class new options
338 command widget (-opt val -opt val ...)
339
340Once created, the pathname to the widget becomes a new command. This new
341*widget command* is the programmer's handle for getting the new widget to
342perform some *action*. In C, you'd express this as someAction(fred,
343someOptions), in C++, you would express this as fred.someAction(someOptions),
344and in Tk, you say::
345
Georg Brandl48310cd2009-01-03 21:18:54 +0000346 .fred someAction someOptions
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348Note that the object name, ``.fred``, starts with a dot.
349
350As you'd expect, the legal values for *someAction* will depend on the widget's
351class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
352does not work if fred is a label (disabling of labels is not supported in Tk).
353
354The legal values of *someOptions* is action dependent. Some actions, like
355``disable``, require no arguments, others, like a text-entry box's ``delete``
356command, would need arguments to specify what range of text to delete.
357
358
359.. _tkinter-basic-mapping:
360
361Mapping Basic Tk into Tkinter
362-----------------------------
363
364Class commands in Tk correspond to class constructors in Tkinter. ::
365
366 button .fred =====> fred = Button()
367
368The master of an object is implicit in the new name given to it at creation
369time. In Tkinter, masters are specified explicitly. ::
370
371 button .panel.fred =====> fred = Button(panel)
372
373The configuration options in Tk are given in lists of hyphened tags followed by
374values. In Tkinter, options are specified as keyword-arguments in the instance
375constructor, and keyword-args for configure calls or as instance indices, in
376dictionary style, for established instances. See section
377:ref:`tkinter-setting-options` on setting options. ::
378
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000379 button .fred -fg red =====> fred = Button(panel, fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000380 .fred configure -fg red =====> fred["fg"] = red
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000381 OR ==> fred.config(fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383In Tk, to perform an action on a widget, use the widget name as a command, and
384follow it with an action name, possibly with arguments (options). In Tkinter,
385you call methods on the class instance to invoke actions on the widget. The
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000386actions (methods) that a given widget can perform are listed in
387:file:`tkinter/__init__.py`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389 .fred invoke =====> fred.invoke()
390
391To give a widget to the packer (geometry manager), you call pack with optional
392arguments. In Tkinter, the Pack class holds all this functionality, and the
393various forms of the pack command are implemented as methods. All widgets in
Georg Brandlac6060c2008-05-17 18:44:45 +0000394:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
Georg Brandl48310cd2009-01-03 21:18:54 +0000395methods. See the :mod:`tkinter.tix` module documentation for additional
Georg Brandlac6060c2008-05-17 18:44:45 +0000396information on the Form geometry manager. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000398 pack .fred -side left =====> fred.pack(side="left")
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400
401How Tk and Tkinter are Related
402------------------------------
403
Georg Brandl116aa622007-08-15 14:28:22 +0000404From the top down:
405
406Your App Here (Python)
Georg Brandlac6060c2008-05-17 18:44:45 +0000407 A Python application makes a :mod:`tkinter` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Georg Brandlac6060c2008-05-17 18:44:45 +0000409tkinter (Python Package)
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000410 This call (say, for example, creating a button widget), is implemented in
411 the :mod:`tkinter` package, which is written in Python. This Python
412 function will parse the commands and the arguments and convert them into a
413 form that makes them look as if they had come from a Tk script instead of
414 a Python script.
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000416_tkinter (C)
Georg Brandl116aa622007-08-15 14:28:22 +0000417 These commands and their arguments will be passed to a C function in the
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000418 :mod:`_tkinter` - note the underscore - extension module.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420Tk Widgets (C and Tcl)
421 This C function is able to make calls into other C modules, including the C
422 functions that make up the Tk library. Tk is implemented in C and some Tcl.
423 The Tcl part of the Tk widgets is used to bind certain default behaviors to
Georg Brandlac6060c2008-05-17 18:44:45 +0000424 widgets, and is executed once at the point where the Python :mod:`tkinter`
425 package is imported. (The user never sees this stage).
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427Tk (C)
428 The Tk part of the Tk Widgets implement the final mapping to ...
429
430Xlib (C)
431 the Xlib library to draw graphics on the screen.
432
433
Miss Islington (bot)2666d702021-08-11 10:16:10 -0700434Threading model
435---------------
436
437Python and Tcl/Tk have very different threading models, which :mod:`tkinter`
438tries to bridge. If you use threads, you may need to be aware of this.
439
440A Python interpreter may have many threads associated with it. In Tcl, multiple
441threads can be created, but each thread has a separate Tcl interpreter instance
442associated with it. Threads can also create more than one interpreter instance,
443though each interpreter instance can be used only by the one thread that created it.
444
445Each :class:`Tk` object created by :mod:`tkinter` contains a Tcl interpreter.
446It also keeps track of which thread created that interpreter. Calls to
447:mod:`tkinter` can be made from any Python thread. Internally, if a call comes
448from a thread other than the one that created the :class:`Tk` object, an event
449is posted to the interpreter's event queue, and when executed, the result is
450returned to the calling Python thread.
451
452Tcl/Tk applications are normally event-driven, meaning that after initialization,
453the interpreter runs an event loop (i.e. :func:`Tk.mainloop`) and responds to events.
454Because it is single-threaded, event handlers must respond quickly, otherwise they
455will block other events from being processed. To avoid this, any long-running
456computations should not run in an event handler, but are either broken into smaller
457pieces using timers, or run in another thread. This is different from many GUI
458toolkits where the GUI runs in a completely separate thread from all application
459code including event handlers.
460
461If the Tcl interpreter is not running the event loop and processing events, any
462:mod:`tkinter` calls made from threads other than the one running the Tcl
463interpreter will fail.
464
465A number of special cases exist:
466
467 * Tcl/Tk libraries can be built so they are not thread-aware. In this case,
468 :mod:`tkinter` calls the library from the originating Python thread, even
469 if this is different than the thread that created the Tcl interpreter. A global
470 lock ensures only one call occurs at a time.
471
472 * While :mod:`tkinter` allows you to create more than one instance of a :class:`Tk`
473 object (with its own interpreter), all interpreters that are part of the same
474 thread share a common event queue, which gets ugly fast. In practice, don't create
475 more than one instance of :class:`Tk` at a time. Otherwise, it's best to create
476 them in separate threads and ensure you're running a thread-aware Tcl/Tk build.
477
478 * Blocking event handlers are not the only way to prevent the Tcl interpreter from
479 reentering the event loop. It is even possible to run multiple nested event loops
480 or abandon the event loop entirely. If you're doing anything tricky when it comes
481 to events or threads, be aware of these possibilities.
482
483 * There are a few select :mod:`tkinter` functions that presently work only when
484 called from the thread that created the Tcl interpreter.
485
486
Georg Brandl116aa622007-08-15 14:28:22 +0000487Handy Reference
488---------------
489
490
491.. _tkinter-setting-options:
492
493Setting Options
494^^^^^^^^^^^^^^^
495
496Options control things like the color and border width of a widget. Options can
497be set in three ways:
498
499At object creation time, using keyword arguments
500 ::
501
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000502 fred = Button(self, fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504After object creation, treating the option name like a dictionary index
505 ::
506
507 fred["fg"] = "red"
508 fred["bg"] = "blue"
509
510Use the config() method to update multiple attrs subsequent to object creation
511 ::
512
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000513 fred.config(fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515For a complete explanation of a given option and its behavior, see the Tk man
516pages for the widget in question.
517
518Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
519for each widget. The former is a list of options that are common to many
520widgets, the latter are the options that are idiosyncratic to that particular
521widget. The Standard Options are documented on the :manpage:`options(3)` man
522page.
523
524No distinction between standard and widget-specific options is made in this
525document. Some options don't apply to some kinds of widgets. Whether a given
526widget responds to a particular option depends on the class of the widget;
527buttons have a ``command`` option, labels do not.
528
529The options supported by a given widget are listed in that widget's man page, or
530can be queried at runtime by calling the :meth:`config` method without
531arguments, or by calling the :meth:`keys` method on that widget. The return
532value of these calls is a dictionary whose key is the name of the option as a
533string (for example, ``'relief'``) and whose values are 5-tuples.
534
535Some options, like ``bg`` are synonyms for common options with long names
536(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
537of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
538back will contain the name of the synonym and the "real" option (such as
539``('bg', 'background')``).
540
541+-------+---------------------------------+--------------+
542| Index | Meaning | Example |
543+=======+=================================+==============+
544| 0 | option name | ``'relief'`` |
545+-------+---------------------------------+--------------+
546| 1 | option name for database lookup | ``'relief'`` |
547+-------+---------------------------------+--------------+
548| 2 | option class for database | ``'Relief'`` |
549| | lookup | |
550+-------+---------------------------------+--------------+
551| 3 | default value | ``'raised'`` |
552+-------+---------------------------------+--------------+
553| 4 | current value | ``'groove'`` |
554+-------+---------------------------------+--------------+
555
556Example::
557
Collin Winterc79461b2007-09-01 23:34:30 +0000558 >>> print(fred.config())
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200559 {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561Of course, the dictionary printed will include all the options available and
562their values. This is meant only as an example.
563
564
565The Packer
566^^^^^^^^^^
567
568.. index:: single: packing (widgets)
569
Georg Brandl116aa622007-08-15 14:28:22 +0000570The packer is one of Tk's geometry-management mechanisms. Geometry managers
Nathan Mecaf9492020-08-02 22:13:03 -0400571are used to specify the relative positioning of widgets within their container -
572their mutual *master*. In contrast to the more cumbersome *placer* (which is
573used less commonly, and we do not cover here), the packer takes qualitative
574relationship specification - *above*, *to the left of*, *filling*, etc - and
575works everything out to determine the exact placement coordinates for you.
Georg Brandl116aa622007-08-15 14:28:22 +0000576
Georg Brandl116aa622007-08-15 14:28:22 +0000577The size of any *master* widget is determined by the size of the "slave widgets"
578inside. The packer is used to control where slave widgets appear inside the
579master into which they are packed. You can pack widgets into frames, and frames
580into other frames, in order to achieve the kind of layout you desire.
581Additionally, the arrangement is dynamically adjusted to accommodate incremental
582changes to the configuration, once it is packed.
583
584Note that widgets do not appear until they have had their geometry specified
585with a geometry manager. It's a common early mistake to leave out the geometry
586specification, and then be surprised when the widget is created but nothing
587appears. A widget will appear only after it has had, for example, the packer's
588:meth:`pack` method applied to it.
589
590The pack() method can be called with keyword-option/value pairs that control
591where the widget is to appear within its container, and how it is to behave when
592the main application window is resized. Here are some examples::
593
594 fred.pack() # defaults to side = "top"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000595 fred.pack(side="left")
596 fred.pack(expand=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000597
598
599Packer Options
600^^^^^^^^^^^^^^
601
602For more extensive information on the packer and the options that it can take,
603see the man pages and page 183 of John Ousterhout's book.
604
Georg Brandl48310cd2009-01-03 21:18:54 +0000605anchor
Georg Brandl116aa622007-08-15 14:28:22 +0000606 Anchor type. Denotes where the packer is to place each slave in its parcel.
607
608expand
609 Boolean, ``0`` or ``1``.
610
611fill
612 Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
613
614ipadx and ipady
615 A distance - designating internal padding on each side of the slave widget.
616
617padx and pady
618 A distance - designating external padding on each side of the slave widget.
619
620side
621 Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
622
623
624Coupling Widget Variables
625^^^^^^^^^^^^^^^^^^^^^^^^^
626
627The current-value setting of some widgets (like text entry widgets) can be
628connected directly to application variables by using special options. These
629options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
630``value``. This connection works both ways: if the variable changes for any
631reason, the widget it's connected to will be updated to reflect the new value.
632
Georg Brandlac6060c2008-05-17 18:44:45 +0000633Unfortunately, in the current implementation of :mod:`tkinter` it is not
Georg Brandl116aa622007-08-15 14:28:22 +0000634possible to hand over an arbitrary Python variable to a widget through a
635``variable`` or ``textvariable`` option. The only kinds of variables for which
636this works are variables that are subclassed from a class called Variable,
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000637defined in :mod:`tkinter`.
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639There are many useful subclasses of Variable already defined:
640:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
641:class:`BooleanVar`. To read the current value of such a variable, call the
Georg Brandl502d9a52009-07-26 15:02:41 +0000642:meth:`get` method on it, and to change its value you call the :meth:`!set`
Georg Brandl116aa622007-08-15 14:28:22 +0000643method. If you follow this protocol, the widget will always track the value of
644the variable, with no further intervention on your part.
645
646For example::
647
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100648 import tkinter as tk
649
650 class App(tk.Frame):
651 def __init__(self, master):
Berker Peksag3093bf12016-07-14 07:32:43 +0300652 super().__init__(master)
Georg Brandl116aa622007-08-15 14:28:22 +0000653 self.pack()
654
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100655 self.entrythingy = tk.Entry()
Georg Brandl116aa622007-08-15 14:28:22 +0000656 self.entrythingy.pack()
657
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100658 # Create the application variable.
659 self.contents = tk.StringVar()
660 # Set it to some value.
Georg Brandl116aa622007-08-15 14:28:22 +0000661 self.contents.set("this is a variable")
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100662 # Tell the entry widget to watch this variable.
Georg Brandl116aa622007-08-15 14:28:22 +0000663 self.entrythingy["textvariable"] = self.contents
664
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100665 # Define a callback for when the user hits return.
666 # It prints the current value of the variable.
Georg Brandl116aa622007-08-15 14:28:22 +0000667 self.entrythingy.bind('<Key-Return>',
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100668 self.print_contents)
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670 def print_contents(self, event):
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100671 print("Hi. The current entry content is:",
Collin Winterc79461b2007-09-01 23:34:30 +0000672 self.contents.get())
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100674 root = tk.Tk()
675 myapp = App(root)
676 myapp.mainloop()
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678The Window Manager
679^^^^^^^^^^^^^^^^^^
680
681.. index:: single: window manager (widgets)
682
Georg Brandl116aa622007-08-15 14:28:22 +0000683In Tk, there is a utility command, ``wm``, for interacting with the window
684manager. Options to the ``wm`` command allow you to control things like titles,
Georg Brandlac6060c2008-05-17 18:44:45 +0000685placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
Georg Brandl116aa622007-08-15 14:28:22 +0000686been implemented as methods on the :class:`Wm` class. Toplevel widgets are
687subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
688directly.
689
690To get at the toplevel window that contains a given widget, you can often just
691refer to the widget's master. Of course if the widget has been packed inside of
692a frame, the master won't represent a toplevel window. To get at the toplevel
693window that contains an arbitrary widget, you can call the :meth:`_root` method.
694This method begins with an underscore to denote the fact that this function is
695part of the implementation, and not an interface to Tk functionality.
696
Georg Brandl116aa622007-08-15 14:28:22 +0000697Here are some examples of typical usage::
698
Berker Peksag3093bf12016-07-14 07:32:43 +0300699 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000700
Berker Peksag3093bf12016-07-14 07:32:43 +0300701 class App(tk.Frame):
702 def __init__(self, master=None):
703 super().__init__(master)
704 self.pack()
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706 # create the application
707 myapp = App()
708
709 #
710 # here are method calls to the window manager class
711 #
712 myapp.master.title("My Do-Nothing Application")
713 myapp.master.maxsize(1000, 400)
714
715 # start the program
716 myapp.mainloop()
717
718
719Tk Option Data Types
720^^^^^^^^^^^^^^^^^^^^
721
722.. index:: single: Tk Option Data Types
723
Georg Brandl116aa622007-08-15 14:28:22 +0000724anchor
725 Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
726 ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
727
728bitmap
729 There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
730 ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
731 ``'warning'``. To specify an X bitmap filename, give the full path to the file,
732 preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
733
734boolean
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +0200735 You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000736
737callback
738 This is any Python function that takes no arguments. For example::
739
740 def print_it():
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000741 print("hi there")
Georg Brandl116aa622007-08-15 14:28:22 +0000742 fred["command"] = print_it
743
744color
745 Colors can be given as the names of X colors in the rgb.txt file, or as strings
746 representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
747 ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
748 represent any legal hex digit. See page 160 of Ousterhout's book for details.
749
750cursor
751 The standard X cursor names from :file:`cursorfont.h` can be used, without the
752 ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
753 string ``"hand2"``. You can also specify a bitmap and mask file of your own.
754 See page 179 of Ousterhout's book.
755
756distance
757 Screen distances can be specified in either pixels or absolute distances.
758 Pixels are given as numbers and absolute distances as strings, with the trailing
759 character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
760 millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
761 as ``"3.5i"``.
762
763font
764 Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
765 positive numbers are measured in points; sizes with negative numbers are
766 measured in pixels.
767
768geometry
769 This is a string of the form ``widthxheight``, where width and height are
770 measured in pixels for most widgets (in characters for widgets displaying text).
771 For example: ``fred["geometry"] = "200x100"``.
772
773justify
774 Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
775 ``"fill"``.
776
777region
778 This is a string with four space-delimited elements, each of which is a legal
779 distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
780 ``"3c 2c 4c 10.43c"`` are all legal regions.
781
782relief
783 Determines what the border style of a widget will be. Legal values are:
784 ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
785
786scrollcommand
Georg Brandl502d9a52009-07-26 15:02:41 +0000787 This is almost always the :meth:`!set` method of some scrollbar widget, but can
Georg Brandl59b44722010-12-30 22:12:40 +0000788 be any widget method that takes a single argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000789
Nikhil80428ed2019-09-10 01:55:34 -0700790wrap
Georg Brandl116aa622007-08-15 14:28:22 +0000791 Must be one of: ``"none"``, ``"char"``, or ``"word"``.
792
Nikhil80428ed2019-09-10 01:55:34 -0700793.. _Bindings-and-Events:
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795Bindings and Events
796^^^^^^^^^^^^^^^^^^^
797
798.. index::
799 single: bind (widgets)
800 single: events (widgets)
801
Georg Brandl116aa622007-08-15 14:28:22 +0000802The bind method from the widget command allows you to watch for certain events
803and to have a callback function trigger when that event type occurs. The form
804of the bind method is::
805
806 def bind(self, sequence, func, add=''):
807
808where:
809
810sequence
811 is a string that denotes the target kind of event. (See the bind man page and
812 page 201 of John Ousterhout's book for details).
813
814func
815 is a Python function, taking one argument, to be invoked when the event occurs.
816 An Event instance will be passed as the argument. (Functions deployed this way
817 are commonly known as *callbacks*.)
818
819add
820 is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
821 this binding is to replace any other bindings that this event is associated
822 with. Passing a ``'+'`` means that this function is to be added to the list
823 of functions bound to this event type.
824
825For example::
826
Berker Peksag3093bf12016-07-14 07:32:43 +0300827 def turn_red(self, event):
Georg Brandl116aa622007-08-15 14:28:22 +0000828 event.widget["activeforeground"] = "red"
829
Berker Peksag3093bf12016-07-14 07:32:43 +0300830 self.button.bind("<Enter>", self.turn_red)
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832Notice how the widget field of the event is being accessed in the
Berker Peksag3093bf12016-07-14 07:32:43 +0300833``turn_red()`` callback. This field contains the widget that caught the X
Georg Brandl116aa622007-08-15 14:28:22 +0000834event. The following table lists the other event fields you can access, and how
835they are denoted in Tk, which can be useful when referring to the Tk man pages.
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000837+----+---------------------+----+---------------------+
838| Tk | Tkinter Event Field | Tk | Tkinter Event Field |
839+====+=====================+====+=====================+
840| %f | focus | %A | char |
841+----+---------------------+----+---------------------+
842| %h | height | %E | send_event |
843+----+---------------------+----+---------------------+
844| %k | keycode | %K | keysym |
845+----+---------------------+----+---------------------+
846| %s | state | %N | keysym_num |
847+----+---------------------+----+---------------------+
848| %t | time | %T | type |
849+----+---------------------+----+---------------------+
850| %w | width | %W | widget |
851+----+---------------------+----+---------------------+
852| %x | x | %X | x_root |
853+----+---------------------+----+---------------------+
854| %y | y | %Y | y_root |
855+----+---------------------+----+---------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857
858The index Parameter
859^^^^^^^^^^^^^^^^^^^
860
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000861A number of widgets require "index" parameters to be passed. These are used to
Georg Brandl116aa622007-08-15 14:28:22 +0000862point at a specific place in a Text widget, or to particular characters in an
863Entry widget, or to particular menu items in a Menu widget.
864
Georg Brandl116aa622007-08-15 14:28:22 +0000865Entry widget indexes (index, view index, etc.)
866 Entry widgets have options that refer to character positions in the text being
Georg Brandlac6060c2008-05-17 18:44:45 +0000867 displayed. You can use these :mod:`tkinter` functions to access these special
Georg Brandl116aa622007-08-15 14:28:22 +0000868 points in text widgets:
869
Georg Brandl116aa622007-08-15 14:28:22 +0000870Text widget indexes
871 The index notation for Text widgets is very rich and is best described in the Tk
872 man pages.
873
874Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
875 Some options and methods for menus manipulate specific menu entries. Anytime a
876 menu index is needed for an option or a parameter, you may pass in:
877
878 * an integer which refers to the numeric position of the entry in the widget,
879 counted from the top, starting with 0;
880
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000881 * the string ``"active"``, which refers to the menu position that is currently
Georg Brandl116aa622007-08-15 14:28:22 +0000882 under the cursor;
883
884 * the string ``"last"`` which refers to the last menu item;
885
886 * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
887 as a y pixel coordinate in the menu's coordinate system;
888
889 * the string ``"none"``, which indicates no menu entry at all, most often used
890 with menu.activate() to deactivate all entries, and finally,
891
892 * a text string that is pattern matched against the label of the menu entry, as
893 scanned from the top of the menu to the bottom. Note that this index type is
894 considered after all the others, which means that matches for menu items
895 labelled ``last``, ``active``, or ``none`` may be interpreted as the above
896 literals, instead.
897
898
899Images
900^^^^^^
901
Andrés Delfino4b685bf2018-04-17 02:34:35 -0300902Images of different formats can be created through the corresponding subclass
903of :class:`tkinter.Image`:
Georg Brandl116aa622007-08-15 14:28:22 +0000904
Andrés Delfino4b685bf2018-04-17 02:34:35 -0300905* :class:`BitmapImage` for images in XBM format.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
Andrés Delfino4b685bf2018-04-17 02:34:35 -0300907* :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter
908 is supported starting with Tk 8.6.
Georg Brandl116aa622007-08-15 14:28:22 +0000909
910Either type of image is created through either the ``file`` or the ``data``
911option (other options are available as well).
912
913The image object can then be used wherever an ``image`` option is supported by
914some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
915reference to the image. When the last Python reference to the image object is
916deleted, the image data is deleted as well, and Tk will display an empty box
917wherever the image was used.
Terry Jan Reedyd9865632015-05-17 14:49:26 -0400918
Andrés Delfinob81ca282018-04-21 09:17:26 -0300919.. seealso::
920
921 The `Pillow <http://python-pillow.org/>`_ package adds support for
922 formats such as BMP, JPEG, TIFF, and WebP, among others.
Terry Jan Reedyd9865632015-05-17 14:49:26 -0400923
924.. _tkinter-file-handlers:
925
926File Handlers
927-------------
928
929Tk allows you to register and unregister a callback function which will be
930called from the Tk mainloop when I/O is possible on a file descriptor.
931Only one handler may be registered per file descriptor. Example code::
932
933 import tkinter
934 widget = tkinter.Tk()
935 mask = tkinter.READABLE | tkinter.WRITABLE
936 widget.tk.createfilehandler(file, mask, callback)
937 ...
938 widget.tk.deletefilehandler(file)
939
940This feature is not available on Windows.
941
942Since you don't know how many bytes are available for reading, you may not
943want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
944:meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods,
945since these will insist on reading a predefined number of bytes.
946For sockets, the :meth:`~socket.socket.recv` or
947:meth:`~socket.socket.recvfrom` methods will work fine; for other files,
948use raw reads or ``os.read(file.fileno(), maxbytecount)``.
949
950
951.. method:: Widget.tk.createfilehandler(file, mask, func)
952
953 Registers the file handler callback function *func*. The *file* argument
954 may either be an object with a :meth:`~io.IOBase.fileno` method (such as
955 a file or socket object), or an integer file descriptor. The *mask*
956 argument is an ORed combination of any of the three constants below.
957 The callback is called as follows::
958
959 callback(file, mask)
960
961
962.. method:: Widget.tk.deletefilehandler(file)
963
964 Unregisters a file handler.
965
966
967.. data:: READABLE
968 WRITABLE
969 EXCEPTION
970
Ankit Chandawalac36dbac2020-08-03 05:03:48 +0100971 Constants used in the *mask* arguments.