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