blob: 6d90e43e33b266049a5faf8cc0b6aa26bf2118d5 [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
Alexander Belopolskyc02cc272010-07-27 14:16:32 +000016is maintained at ActiveState.) You can check that :mod:`tkinter` is properly
17installed on your system by running ``python -m tkinter`` from the command line;
18this should open a window demonstrating a simple Tk interface.
Georg Brandl116aa622007-08-15 14:28:22 +000019
Georg Brandl116aa622007-08-15 14:28:22 +000020.. seealso::
21
Zachary Ware08863992014-03-18 09:19:18 -050022 `Python Tkinter Resources <https://wiki.python.org/moin/TkInter>`_
Georg Brandl116aa622007-08-15 14:28:22 +000023 The Python Tkinter Topic Guide provides a great deal of information on using Tk
24 from Python and links to other sources of information on Tk.
25
Andrew Svetlove708a8a2012-07-26 17:02:57 +030026 `TKDocs <http://www.tkdocs.com/>`_
27 Extensive tutorial plus friendlier widget pages for some of the widgets.
28
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030029 `Tkinter reference: a GUI for Python <https://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030030 On-line reference material.
31
32 `Tkinter docs from effbot <http://effbot.org/tkinterbook/>`_
33 Online reference for tkinter supported by effbot.org.
34
Serhiy Storchaka6dff0202016-05-07 10:49:07 +030035 `Tcl/Tk manual <https://www.tcl.tk/man/tcl8.5/>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030036 Official manual for the latest tcl/tk version.
37
Sanyam Khurana338cd832018-01-20 05:55:37 +053038 `Programming Python <http://learning-python.com/about-pp4e.html>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030039 Book by Mark Lutz, has excellent coverage of Tkinter.
40
Sanyam Khurana1b4587a2017-12-06 22:09:33 +053041 `Modern Tkinter for Busy Python Developers <https://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/>`_
Andrew Svetlove708a8a2012-07-26 17:02:57 +030042 Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.
43
Georg Brandl5d941342016-02-26 19:37:12 +010044 `Python and Tkinter Programming <https://www.manning.com/books/python-and-tkinter-programming>`_
Georg Brandl116aa622007-08-15 14:28:22 +000045 The book by John Grayson (ISBN 1-884777-81-3).
46
47
48Tkinter Modules
49---------------
50
Ezio Melotti1a263ad2010-03-14 09:51:37 +000051Most of the time, :mod:`tkinter` is all you really need, but a number of
52additional modules are available as well. The Tk interface is located in a
Georg Brandl116aa622007-08-15 14:28:22 +000053binary module named :mod:`_tkinter`. This module contains the low-level
54interface to Tk, and should never be used directly by application programmers.
55It is usually a shared library (or DLL), but might in some cases be statically
56linked with the Python interpreter.
57
Georg Brandlac6060c2008-05-17 18:44:45 +000058In addition to the Tk interface module, :mod:`tkinter` includes a number of
Georg Brandl48310cd2009-01-03 21:18:54 +000059Python modules, :mod:`tkinter.constants` being one of the most important.
Georg Brandlac6060c2008-05-17 18:44:45 +000060Importing :mod:`tkinter` will automatically import :mod:`tkinter.constants`,
61so, usually, to use Tkinter all you need is a simple import statement::
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandlac6060c2008-05-17 18:44:45 +000063 import tkinter
Georg Brandl116aa622007-08-15 14:28:22 +000064
65Or, more often::
66
Georg Brandlac6060c2008-05-17 18:44:45 +000067 from tkinter import *
Georg Brandl116aa622007-08-15 14:28:22 +000068
69
70.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
71
72 The :class:`Tk` class is instantiated without arguments. This creates a toplevel
73 widget of Tk which usually is the main window of an application. Each instance
74 has its own associated Tcl interpreter.
75
Christian Heimes5b5e81c2007-12-31 16:14:33 +000076 .. FIXME: The following keyword arguments are currently recognized:
Georg Brandl116aa622007-08-15 14:28:22 +000077
Georg Brandl116aa622007-08-15 14:28:22 +000078
79.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
80
81 The :func:`Tcl` function is a factory function which creates an object much like
82 that created by the :class:`Tk` class, except that it does not initialize the Tk
83 subsystem. This is most often useful when driving the Tcl interpreter in an
84 environment where one doesn't want to create extraneous toplevel windows, or
85 where one cannot (such as Unix/Linux systems without an X server). An object
86 created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
87 subsystem initialized) by calling its :meth:`loadtk` method.
88
Georg Brandl116aa622007-08-15 14:28:22 +000089
90Other modules that provide Tk support include:
91
Georg Brandlac6060c2008-05-17 18:44:45 +000092:mod:`tkinter.scrolledtext`
Georg Brandl116aa622007-08-15 14:28:22 +000093 Text widget with a vertical scroll bar built in.
94
Georg Brandlac6060c2008-05-17 18:44:45 +000095:mod:`tkinter.colorchooser`
Georg Brandl116aa622007-08-15 14:28:22 +000096 Dialog to let the user choose a color.
97
Georg Brandlac6060c2008-05-17 18:44:45 +000098:mod:`tkinter.commondialog`
Georg Brandl116aa622007-08-15 14:28:22 +000099 Base class for the dialogs defined in the other modules listed here.
100
Georg Brandlac6060c2008-05-17 18:44:45 +0000101:mod:`tkinter.filedialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000102 Common dialogs to allow the user to specify a file to open or save.
103
Georg Brandlac6060c2008-05-17 18:44:45 +0000104:mod:`tkinter.font`
Georg Brandl116aa622007-08-15 14:28:22 +0000105 Utilities to help work with fonts.
106
Georg Brandlac6060c2008-05-17 18:44:45 +0000107:mod:`tkinter.messagebox`
Georg Brandl116aa622007-08-15 14:28:22 +0000108 Access to standard Tk dialog boxes.
109
Georg Brandlac6060c2008-05-17 18:44:45 +0000110:mod:`tkinter.simpledialog`
Georg Brandl116aa622007-08-15 14:28:22 +0000111 Basic dialogs and convenience functions.
112
Georg Brandlac6060c2008-05-17 18:44:45 +0000113:mod:`tkinter.dnd`
Georg Brandl48310cd2009-01-03 21:18:54 +0000114 Drag-and-drop support for :mod:`tkinter`. This is experimental and should
Georg Brandlac6060c2008-05-17 18:44:45 +0000115 become deprecated when it is replaced with the Tk DND.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
Georg Brandl23d11d32008-09-21 07:50:52 +0000117:mod:`turtle`
Georg Brandl116aa622007-08-15 14:28:22 +0000118 Turtle graphics in a Tk window.
119
120
121Tkinter Life Preserver
122----------------------
123
124.. sectionauthor:: Matt Conway
125
126
127This section is not designed to be an exhaustive tutorial on either Tk or
128Tkinter. Rather, it is intended as a stop gap, providing some introductory
129orientation on the system.
130
Georg Brandl116aa622007-08-15 14:28:22 +0000131Credits:
132
Georg Brandl116aa622007-08-15 14:28:22 +0000133* Tk was written by John Ousterhout while at Berkeley.
134
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000135* Tkinter was written by Steen Lumholt and Guido van Rossum.
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137* This Life Preserver was written by Matt Conway at the University of Virginia.
138
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000139* The HTML rendering, and some liberal editing, was produced from a FrameMaker
Georg Brandl116aa622007-08-15 14:28:22 +0000140 version by Ken Manheimer.
141
142* Fredrik Lundh elaborated and revised the class interface descriptions, to get
143 them current with Tk 4.2.
144
145* Mike Clarkson converted the documentation to LaTeX, and compiled the User
146 Interface chapter of the reference manual.
147
148
149How To Use This Section
150^^^^^^^^^^^^^^^^^^^^^^^
151
152This section is designed in two parts: the first half (roughly) covers
153background material, while the second half can be taken to the keyboard as a
154handy reference.
155
156When trying to answer questions of the form "how do I do blah", it is often best
Julien Palardae342cf2017-12-05 06:05:33 +0100157to find out how to do "blah" in straight Tk, and then convert this back into the
Georg Brandlac6060c2008-05-17 18:44:45 +0000158corresponding :mod:`tkinter` call. Python programmers can often guess at the
Georg Brandl116aa622007-08-15 14:28:22 +0000159correct Python command by looking at the Tk documentation. This means that in
160order to use Tkinter, you will have to know a little bit about Tk. This document
161can't fulfill that role, so the best we can do is point you to the best
162documentation that exists. Here are some hints:
163
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000164* The authors strongly suggest getting a copy of the Tk man pages.
165 Specifically, the man pages in the ``manN`` directory are most useful.
166 The ``man3`` man pages describe the C interface to the Tk library and thus
167 are not especially helpful for script writers.
Georg Brandl116aa622007-08-15 14:28:22 +0000168
169* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
170 Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
171 the novice. The book is not exhaustive, and for many details it defers to the
172 man pages.
173
Georg Brandl48310cd2009-01-03 21:18:54 +0000174* :file:`tkinter/__init__.py` is a last resort for most, but can be a good
Georg Brandlac6060c2008-05-17 18:44:45 +0000175 place to go when nothing else makes sense.
Georg Brandl116aa622007-08-15 14:28:22 +0000176
177
178.. seealso::
179
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300180 `Tcl/Tk 8.6 man pages <https://www.tcl.tk/man/tcl8.6/>`_
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000181 The Tcl/Tk manual on www.tcl.tk.
182
Georg Brandl116aa622007-08-15 14:28:22 +0000183 `ActiveState Tcl Home Page <http://tcl.activestate.com/>`_
184 The Tk/Tcl development is largely taking place at ActiveState.
185
Sanyam Khurana1b4587a2017-12-06 22:09:33 +0530186 `Tcl and the Tk Toolkit <https://www.amazon.com/exec/obidos/ASIN/020163337X>`_
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +0200187 The book by John Ousterhout, the inventor of Tcl.
Georg Brandl116aa622007-08-15 14:28:22 +0000188
Benjamin Peterson8c69ecf2015-03-07 09:34:16 -0500189 `Practical Programming in Tcl and Tk <http://www.beedub.com/book/>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000190 Brent Welch's encyclopedic book.
191
192
193A Simple Hello World Program
194^^^^^^^^^^^^^^^^^^^^^^^^^^^^
195
Georg Brandl116aa622007-08-15 14:28:22 +0000196::
197
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700198 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000199
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700200 class Application(tk.Frame):
201 def __init__(self, master=None):
Berker Peksag3093bf12016-07-14 07:32:43 +0300202 super().__init__(master)
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700203 self.pack()
Berker Peksag3093bf12016-07-14 07:32:43 +0300204 self.create_widgets()
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Berker Peksag3093bf12016-07-14 07:32:43 +0300206 def create_widgets(self):
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700207 self.hi_there = tk.Button(self)
208 self.hi_there["text"] = "Hello World\n(click me)"
209 self.hi_there["command"] = self.say_hi
210 self.hi_there.pack(side="top")
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Berker Peksag3093bf12016-07-14 07:32:43 +0300212 self.quit = tk.Button(self, text="QUIT", fg="red",
Serhiy Storchakadba90392016-05-10 12:01:23 +0300213 command=root.destroy)
Berker Peksag3093bf12016-07-14 07:32:43 +0300214 self.quit.pack(side="bottom")
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700216 def say_hi(self):
217 print("hi there, everyone!")
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Andrew Svetlovd3d7c902012-03-14 21:41:23 -0700219 root = tk.Tk()
220 app = Application(master=root)
221 app.mainloop()
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223
224A (Very) Quick Look at Tcl/Tk
225-----------------------------
226
227The class hierarchy looks complicated, but in actual practice, application
228programmers almost always refer to the classes at the very bottom of the
229hierarchy.
230
Georg Brandl116aa622007-08-15 14:28:22 +0000231Notes:
232
233* These classes are provided for the purposes of organizing certain functions
234 under one namespace. They aren't meant to be instantiated independently.
235
236* The :class:`Tk` class is meant to be instantiated only once in an application.
237 Application programmers need not instantiate one explicitly, the system creates
238 one whenever any of the other classes are instantiated.
239
240* The :class:`Widget` class is not meant to be instantiated, it is meant only
241 for subclassing to make "real" widgets (in C++, this is called an 'abstract
242 class').
243
244To make use of this reference material, there will be times when you will need
245to know how to read short passages of Tk and how to identify the various parts
246of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
Georg Brandlac6060c2008-05-17 18:44:45 +0000247:mod:`tkinter` equivalents of what's below.)
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
250of tokens separated by spaces. A Tk widget is just its *class*, the *options*
251that help configure it, and the *actions* that make it do useful things.
252
253To make a widget in Tk, the command is always of the form::
254
255 classCommand newPathname options
256
257*classCommand*
258 denotes which kind of widget to make (a button, a label, a menu...)
259
260*newPathname*
261 is the new name for this widget. All names in Tk must be unique. To help
262 enforce this, widgets in Tk are named with *pathnames*, just like files in a
263 file system. The top level widget, the *root*, is called ``.`` (period) and
264 children are delimited by more periods. For example,
265 ``.myApp.controlPanel.okButton`` might be the name of a widget.
266
267*options*
268 configure the widget's appearance and in some cases, its behavior. The options
269 come in the form of a list of flags and values. Flags are preceded by a '-',
270 like Unix shell command flags, and values are put in quotes if they are more
271 than one word.
272
273For example::
274
275 button .fred -fg red -text "hi there"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000276 ^ ^ \______________________/
Georg Brandl116aa622007-08-15 14:28:22 +0000277 | | |
278 class new options
279 command widget (-opt val -opt val ...)
280
281Once created, the pathname to the widget becomes a new command. This new
282*widget command* is the programmer's handle for getting the new widget to
283perform some *action*. In C, you'd express this as someAction(fred,
284someOptions), in C++, you would express this as fred.someAction(someOptions),
285and in Tk, you say::
286
Georg Brandl48310cd2009-01-03 21:18:54 +0000287 .fred someAction someOptions
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289Note that the object name, ``.fred``, starts with a dot.
290
291As you'd expect, the legal values for *someAction* will depend on the widget's
292class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
293does not work if fred is a label (disabling of labels is not supported in Tk).
294
295The legal values of *someOptions* is action dependent. Some actions, like
296``disable``, require no arguments, others, like a text-entry box's ``delete``
297command, would need arguments to specify what range of text to delete.
298
299
300.. _tkinter-basic-mapping:
301
302Mapping Basic Tk into Tkinter
303-----------------------------
304
305Class commands in Tk correspond to class constructors in Tkinter. ::
306
307 button .fred =====> fred = Button()
308
309The master of an object is implicit in the new name given to it at creation
310time. In Tkinter, masters are specified explicitly. ::
311
312 button .panel.fred =====> fred = Button(panel)
313
314The configuration options in Tk are given in lists of hyphened tags followed by
315values. In Tkinter, options are specified as keyword-arguments in the instance
316constructor, and keyword-args for configure calls or as instance indices, in
317dictionary style, for established instances. See section
318:ref:`tkinter-setting-options` on setting options. ::
319
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000320 button .fred -fg red =====> fred = Button(panel, fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000321 .fred configure -fg red =====> fred["fg"] = red
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000322 OR ==> fred.config(fg="red")
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324In Tk, to perform an action on a widget, use the widget name as a command, and
325follow it with an action name, possibly with arguments (options). In Tkinter,
326you call methods on the class instance to invoke actions on the widget. The
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000327actions (methods) that a given widget can perform are listed in
328:file:`tkinter/__init__.py`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330 .fred invoke =====> fred.invoke()
331
332To give a widget to the packer (geometry manager), you call pack with optional
333arguments. In Tkinter, the Pack class holds all this functionality, and the
334various forms of the pack command are implemented as methods. All widgets in
Georg Brandlac6060c2008-05-17 18:44:45 +0000335:mod:`tkinter` are subclassed from the Packer, and so inherit all the packing
Georg Brandl48310cd2009-01-03 21:18:54 +0000336methods. See the :mod:`tkinter.tix` module documentation for additional
Georg Brandlac6060c2008-05-17 18:44:45 +0000337information on the Form geometry manager. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000339 pack .fred -side left =====> fred.pack(side="left")
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341
342How Tk and Tkinter are Related
343------------------------------
344
Georg Brandl116aa622007-08-15 14:28:22 +0000345From the top down:
346
347Your App Here (Python)
Georg Brandlac6060c2008-05-17 18:44:45 +0000348 A Python application makes a :mod:`tkinter` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Georg Brandlac6060c2008-05-17 18:44:45 +0000350tkinter (Python Package)
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000351 This call (say, for example, creating a button widget), is implemented in
352 the :mod:`tkinter` package, which is written in Python. This Python
353 function will parse the commands and the arguments and convert them into a
354 form that makes them look as if they had come from a Tk script instead of
355 a Python script.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000357_tkinter (C)
Georg Brandl116aa622007-08-15 14:28:22 +0000358 These commands and their arguments will be passed to a C function in the
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000359 :mod:`_tkinter` - note the underscore - extension module.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361Tk Widgets (C and Tcl)
362 This C function is able to make calls into other C modules, including the C
363 functions that make up the Tk library. Tk is implemented in C and some Tcl.
364 The Tcl part of the Tk widgets is used to bind certain default behaviors to
Georg Brandlac6060c2008-05-17 18:44:45 +0000365 widgets, and is executed once at the point where the Python :mod:`tkinter`
366 package is imported. (The user never sees this stage).
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368Tk (C)
369 The Tk part of the Tk Widgets implement the final mapping to ...
370
371Xlib (C)
372 the Xlib library to draw graphics on the screen.
373
374
375Handy Reference
376---------------
377
378
379.. _tkinter-setting-options:
380
381Setting Options
382^^^^^^^^^^^^^^^
383
384Options control things like the color and border width of a widget. Options can
385be set in three ways:
386
387At object creation time, using keyword arguments
388 ::
389
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000390 fred = Button(self, fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392After object creation, treating the option name like a dictionary index
393 ::
394
395 fred["fg"] = "red"
396 fred["bg"] = "blue"
397
398Use the config() method to update multiple attrs subsequent to object creation
399 ::
400
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000401 fred.config(fg="red", bg="blue")
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403For a complete explanation of a given option and its behavior, see the Tk man
404pages for the widget in question.
405
406Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
407for each widget. The former is a list of options that are common to many
408widgets, the latter are the options that are idiosyncratic to that particular
409widget. The Standard Options are documented on the :manpage:`options(3)` man
410page.
411
412No distinction between standard and widget-specific options is made in this
413document. Some options don't apply to some kinds of widgets. Whether a given
414widget responds to a particular option depends on the class of the widget;
415buttons have a ``command`` option, labels do not.
416
417The options supported by a given widget are listed in that widget's man page, or
418can be queried at runtime by calling the :meth:`config` method without
419arguments, or by calling the :meth:`keys` method on that widget. The return
420value of these calls is a dictionary whose key is the name of the option as a
421string (for example, ``'relief'``) and whose values are 5-tuples.
422
423Some options, like ``bg`` are synonyms for common options with long names
424(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
425of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
426back will contain the name of the synonym and the "real" option (such as
427``('bg', 'background')``).
428
429+-------+---------------------------------+--------------+
430| Index | Meaning | Example |
431+=======+=================================+==============+
432| 0 | option name | ``'relief'`` |
433+-------+---------------------------------+--------------+
434| 1 | option name for database lookup | ``'relief'`` |
435+-------+---------------------------------+--------------+
436| 2 | option class for database | ``'Relief'`` |
437| | lookup | |
438+-------+---------------------------------+--------------+
439| 3 | default value | ``'raised'`` |
440+-------+---------------------------------+--------------+
441| 4 | current value | ``'groove'`` |
442+-------+---------------------------------+--------------+
443
444Example::
445
Collin Winterc79461b2007-09-01 23:34:30 +0000446 >>> print(fred.config())
Serhiy Storchakaf47036c2013-12-24 11:04:36 +0200447 {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}
Georg Brandl116aa622007-08-15 14:28:22 +0000448
449Of course, the dictionary printed will include all the options available and
450their values. This is meant only as an example.
451
452
453The Packer
454^^^^^^^^^^
455
456.. index:: single: packing (widgets)
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458The packer is one of Tk's geometry-management mechanisms. Geometry managers
459are used to specify the relative positioning of the positioning of widgets
460within their container - their mutual *master*. In contrast to the more
461cumbersome *placer* (which is used less commonly, and we do not cover here), the
462packer takes qualitative relationship specification - *above*, *to the left of*,
463*filling*, etc - and works everything out to determine the exact placement
464coordinates for you.
465
Georg Brandl116aa622007-08-15 14:28:22 +0000466The size of any *master* widget is determined by the size of the "slave widgets"
467inside. The packer is used to control where slave widgets appear inside the
468master into which they are packed. You can pack widgets into frames, and frames
469into other frames, in order to achieve the kind of layout you desire.
470Additionally, the arrangement is dynamically adjusted to accommodate incremental
471changes to the configuration, once it is packed.
472
473Note that widgets do not appear until they have had their geometry specified
474with a geometry manager. It's a common early mistake to leave out the geometry
475specification, and then be surprised when the widget is created but nothing
476appears. A widget will appear only after it has had, for example, the packer's
477:meth:`pack` method applied to it.
478
479The pack() method can be called with keyword-option/value pairs that control
480where the widget is to appear within its container, and how it is to behave when
481the main application window is resized. Here are some examples::
482
483 fred.pack() # defaults to side = "top"
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000484 fred.pack(side="left")
485 fred.pack(expand=1)
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487
488Packer Options
489^^^^^^^^^^^^^^
490
491For more extensive information on the packer and the options that it can take,
492see the man pages and page 183 of John Ousterhout's book.
493
Georg Brandl48310cd2009-01-03 21:18:54 +0000494anchor
Georg Brandl116aa622007-08-15 14:28:22 +0000495 Anchor type. Denotes where the packer is to place each slave in its parcel.
496
497expand
498 Boolean, ``0`` or ``1``.
499
500fill
501 Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
502
503ipadx and ipady
504 A distance - designating internal padding on each side of the slave widget.
505
506padx and pady
507 A distance - designating external padding on each side of the slave widget.
508
509side
510 Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
511
512
513Coupling Widget Variables
514^^^^^^^^^^^^^^^^^^^^^^^^^
515
516The current-value setting of some widgets (like text entry widgets) can be
517connected directly to application variables by using special options. These
518options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
519``value``. This connection works both ways: if the variable changes for any
520reason, the widget it's connected to will be updated to reflect the new value.
521
Georg Brandlac6060c2008-05-17 18:44:45 +0000522Unfortunately, in the current implementation of :mod:`tkinter` it is not
Georg Brandl116aa622007-08-15 14:28:22 +0000523possible to hand over an arbitrary Python variable to a widget through a
524``variable`` or ``textvariable`` option. The only kinds of variables for which
525this works are variables that are subclassed from a class called Variable,
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000526defined in :mod:`tkinter`.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
528There are many useful subclasses of Variable already defined:
529:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
530:class:`BooleanVar`. To read the current value of such a variable, call the
Georg Brandl502d9a52009-07-26 15:02:41 +0000531:meth:`get` method on it, and to change its value you call the :meth:`!set`
Georg Brandl116aa622007-08-15 14:28:22 +0000532method. If you follow this protocol, the widget will always track the value of
533the variable, with no further intervention on your part.
534
535For example::
536
537 class App(Frame):
538 def __init__(self, master=None):
Berker Peksag3093bf12016-07-14 07:32:43 +0300539 super().__init__(master)
Georg Brandl116aa622007-08-15 14:28:22 +0000540 self.pack()
541
542 self.entrythingy = Entry()
543 self.entrythingy.pack()
544
545 # here is the application variable
546 self.contents = StringVar()
547 # set it to some value
548 self.contents.set("this is a variable")
549 # tell the entry widget to watch this variable
550 self.entrythingy["textvariable"] = self.contents
551
552 # and here we get a callback when the user hits return.
553 # we will have the program print out the value of the
554 # application variable when the user hits return
555 self.entrythingy.bind('<Key-Return>',
556 self.print_contents)
557
558 def print_contents(self, event):
Collin Winterc79461b2007-09-01 23:34:30 +0000559 print("hi. contents of entry is now ---->",
560 self.contents.get())
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562
563The Window Manager
564^^^^^^^^^^^^^^^^^^
565
566.. index:: single: window manager (widgets)
567
Georg Brandl116aa622007-08-15 14:28:22 +0000568In Tk, there is a utility command, ``wm``, for interacting with the window
569manager. Options to the ``wm`` command allow you to control things like titles,
Georg Brandlac6060c2008-05-17 18:44:45 +0000570placement, icon bitmaps, and the like. In :mod:`tkinter`, these commands have
Georg Brandl116aa622007-08-15 14:28:22 +0000571been implemented as methods on the :class:`Wm` class. Toplevel widgets are
572subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
573directly.
574
575To get at the toplevel window that contains a given widget, you can often just
576refer to the widget's master. Of course if the widget has been packed inside of
577a frame, the master won't represent a toplevel window. To get at the toplevel
578window that contains an arbitrary widget, you can call the :meth:`_root` method.
579This method begins with an underscore to denote the fact that this function is
580part of the implementation, and not an interface to Tk functionality.
581
Georg Brandl116aa622007-08-15 14:28:22 +0000582Here are some examples of typical usage::
583
Berker Peksag3093bf12016-07-14 07:32:43 +0300584 import tkinter as tk
Georg Brandl116aa622007-08-15 14:28:22 +0000585
Berker Peksag3093bf12016-07-14 07:32:43 +0300586 class App(tk.Frame):
587 def __init__(self, master=None):
588 super().__init__(master)
589 self.pack()
Georg Brandl116aa622007-08-15 14:28:22 +0000590
591 # create the application
592 myapp = App()
593
594 #
595 # here are method calls to the window manager class
596 #
597 myapp.master.title("My Do-Nothing Application")
598 myapp.master.maxsize(1000, 400)
599
600 # start the program
601 myapp.mainloop()
602
603
604Tk Option Data Types
605^^^^^^^^^^^^^^^^^^^^
606
607.. index:: single: Tk Option Data Types
608
Georg Brandl116aa622007-08-15 14:28:22 +0000609anchor
610 Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
611 ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
612
613bitmap
614 There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
615 ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
616 ``'warning'``. To specify an X bitmap filename, give the full path to the file,
617 preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
618
619boolean
Serhiy Storchakaa4d170d2013-12-23 18:20:51 +0200620 You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622callback
623 This is any Python function that takes no arguments. For example::
624
625 def print_it():
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000626 print("hi there")
Georg Brandl116aa622007-08-15 14:28:22 +0000627 fred["command"] = print_it
628
629color
630 Colors can be given as the names of X colors in the rgb.txt file, or as strings
631 representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
632 ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
633 represent any legal hex digit. See page 160 of Ousterhout's book for details.
634
635cursor
636 The standard X cursor names from :file:`cursorfont.h` can be used, without the
637 ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
638 string ``"hand2"``. You can also specify a bitmap and mask file of your own.
639 See page 179 of Ousterhout's book.
640
641distance
642 Screen distances can be specified in either pixels or absolute distances.
643 Pixels are given as numbers and absolute distances as strings, with the trailing
644 character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
645 millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
646 as ``"3.5i"``.
647
648font
649 Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
650 positive numbers are measured in points; sizes with negative numbers are
651 measured in pixels.
652
653geometry
654 This is a string of the form ``widthxheight``, where width and height are
655 measured in pixels for most widgets (in characters for widgets displaying text).
656 For example: ``fred["geometry"] = "200x100"``.
657
658justify
659 Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
660 ``"fill"``.
661
662region
663 This is a string with four space-delimited elements, each of which is a legal
664 distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
665 ``"3c 2c 4c 10.43c"`` are all legal regions.
666
667relief
668 Determines what the border style of a widget will be. Legal values are:
669 ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
670
671scrollcommand
Georg Brandl502d9a52009-07-26 15:02:41 +0000672 This is almost always the :meth:`!set` method of some scrollbar widget, but can
Georg Brandl59b44722010-12-30 22:12:40 +0000673 be any widget method that takes a single argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675wrap:
676 Must be one of: ``"none"``, ``"char"``, or ``"word"``.
677
678
679Bindings and Events
680^^^^^^^^^^^^^^^^^^^
681
682.. index::
683 single: bind (widgets)
684 single: events (widgets)
685
Georg Brandl116aa622007-08-15 14:28:22 +0000686The bind method from the widget command allows you to watch for certain events
687and to have a callback function trigger when that event type occurs. The form
688of the bind method is::
689
690 def bind(self, sequence, func, add=''):
691
692where:
693
694sequence
695 is a string that denotes the target kind of event. (See the bind man page and
696 page 201 of John Ousterhout's book for details).
697
698func
699 is a Python function, taking one argument, to be invoked when the event occurs.
700 An Event instance will be passed as the argument. (Functions deployed this way
701 are commonly known as *callbacks*.)
702
703add
704 is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
705 this binding is to replace any other bindings that this event is associated
706 with. Passing a ``'+'`` means that this function is to be added to the list
707 of functions bound to this event type.
708
709For example::
710
Berker Peksag3093bf12016-07-14 07:32:43 +0300711 def turn_red(self, event):
Georg Brandl116aa622007-08-15 14:28:22 +0000712 event.widget["activeforeground"] = "red"
713
Berker Peksag3093bf12016-07-14 07:32:43 +0300714 self.button.bind("<Enter>", self.turn_red)
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716Notice how the widget field of the event is being accessed in the
Berker Peksag3093bf12016-07-14 07:32:43 +0300717``turn_red()`` callback. This field contains the widget that caught the X
Georg Brandl116aa622007-08-15 14:28:22 +0000718event. The following table lists the other event fields you can access, and how
719they are denoted in Tk, which can be useful when referring to the Tk man pages.
Georg Brandl116aa622007-08-15 14:28:22 +0000720
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000721+----+---------------------+----+---------------------+
722| Tk | Tkinter Event Field | Tk | Tkinter Event Field |
723+====+=====================+====+=====================+
724| %f | focus | %A | char |
725+----+---------------------+----+---------------------+
726| %h | height | %E | send_event |
727+----+---------------------+----+---------------------+
728| %k | keycode | %K | keysym |
729+----+---------------------+----+---------------------+
730| %s | state | %N | keysym_num |
731+----+---------------------+----+---------------------+
732| %t | time | %T | type |
733+----+---------------------+----+---------------------+
734| %w | width | %W | widget |
735+----+---------------------+----+---------------------+
736| %x | x | %X | x_root |
737+----+---------------------+----+---------------------+
738| %y | y | %Y | y_root |
739+----+---------------------+----+---------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
742The index Parameter
743^^^^^^^^^^^^^^^^^^^
744
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000745A number of widgets require "index" parameters to be passed. These are used to
Georg Brandl116aa622007-08-15 14:28:22 +0000746point at a specific place in a Text widget, or to particular characters in an
747Entry widget, or to particular menu items in a Menu widget.
748
Georg Brandl116aa622007-08-15 14:28:22 +0000749Entry widget indexes (index, view index, etc.)
750 Entry widgets have options that refer to character positions in the text being
Georg Brandlac6060c2008-05-17 18:44:45 +0000751 displayed. You can use these :mod:`tkinter` functions to access these special
Georg Brandl116aa622007-08-15 14:28:22 +0000752 points in text widgets:
753
Georg Brandl116aa622007-08-15 14:28:22 +0000754Text widget indexes
755 The index notation for Text widgets is very rich and is best described in the Tk
756 man pages.
757
758Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
759 Some options and methods for menus manipulate specific menu entries. Anytime a
760 menu index is needed for an option or a parameter, you may pass in:
761
762 * an integer which refers to the numeric position of the entry in the widget,
763 counted from the top, starting with 0;
764
Ezio Melotti1a263ad2010-03-14 09:51:37 +0000765 * the string ``"active"``, which refers to the menu position that is currently
Georg Brandl116aa622007-08-15 14:28:22 +0000766 under the cursor;
767
768 * the string ``"last"`` which refers to the last menu item;
769
770 * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
771 as a y pixel coordinate in the menu's coordinate system;
772
773 * the string ``"none"``, which indicates no menu entry at all, most often used
774 with menu.activate() to deactivate all entries, and finally,
775
776 * a text string that is pattern matched against the label of the menu entry, as
777 scanned from the top of the menu to the bottom. Note that this index type is
778 considered after all the others, which means that matches for menu items
779 labelled ``last``, ``active``, or ``none`` may be interpreted as the above
780 literals, instead.
781
782
783Images
784^^^^^^
785
786Bitmap/Pixelmap images can be created through the subclasses of
Georg Brandlac6060c2008-05-17 18:44:45 +0000787:class:`tkinter.Image`:
Georg Brandl116aa622007-08-15 14:28:22 +0000788
789* :class:`BitmapImage` can be used for X11 bitmap data.
790
791* :class:`PhotoImage` can be used for GIF and PPM/PGM color bitmaps.
792
793Either type of image is created through either the ``file`` or the ``data``
794option (other options are available as well).
795
796The image object can then be used wherever an ``image`` option is supported by
797some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
798reference to the image. When the last Python reference to the image object is
799deleted, the image data is deleted as well, and Tk will display an empty box
800wherever the image was used.
Terry Jan Reedyd9865632015-05-17 14:49:26 -0400801
802
803.. _tkinter-file-handlers:
804
805File Handlers
806-------------
807
808Tk allows you to register and unregister a callback function which will be
809called from the Tk mainloop when I/O is possible on a file descriptor.
810Only one handler may be registered per file descriptor. Example code::
811
812 import tkinter
813 widget = tkinter.Tk()
814 mask = tkinter.READABLE | tkinter.WRITABLE
815 widget.tk.createfilehandler(file, mask, callback)
816 ...
817 widget.tk.deletefilehandler(file)
818
819This feature is not available on Windows.
820
821Since you don't know how many bytes are available for reading, you may not
822want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
823:meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods,
824since these will insist on reading a predefined number of bytes.
825For sockets, the :meth:`~socket.socket.recv` or
826:meth:`~socket.socket.recvfrom` methods will work fine; for other files,
827use raw reads or ``os.read(file.fileno(), maxbytecount)``.
828
829
830.. method:: Widget.tk.createfilehandler(file, mask, func)
831
832 Registers the file handler callback function *func*. The *file* argument
833 may either be an object with a :meth:`~io.IOBase.fileno` method (such as
834 a file or socket object), or an integer file descriptor. The *mask*
835 argument is an ORed combination of any of the three constants below.
836 The callback is called as follows::
837
838 callback(file, mask)
839
840
841.. method:: Widget.tk.deletefilehandler(file)
842
843 Unregisters a file handler.
844
845
846.. data:: READABLE
847 WRITABLE
848 EXCEPTION
849
850 Constants used in the *mask* arguments.