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