/Doc/library/tkinter.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 810 lines · 577 code · 233 blank · 0 comment · 0 complexity · cd73abc3503766279796d7fb03cd5add MD5 · raw file

  1. :mod:`Tkinter` --- Python interface to Tcl/Tk
  2. =============================================
  3. .. module:: Tkinter
  4. :synopsis: Interface to Tcl/Tk for graphical user interfaces
  5. .. moduleauthor:: Guido van Rossum <guido@Python.org>
  6. The :mod:`Tkinter` module ("Tk interface") is the standard Python interface to
  7. the Tk GUI toolkit. Both Tk and :mod:`Tkinter` are available on most Unix
  8. platforms, as well as on Windows systems. (Tk itself is not part of Python; it
  9. is maintained at ActiveState.)
  10. .. note::
  11. :mod:`Tkinter` has been renamed to :mod:`tkinter` in Python 3.0. The
  12. :term:`2to3` tool will automatically adapt imports when converting your
  13. sources to 3.0.
  14. .. seealso::
  15. `Python Tkinter Resources <http://www.python.org/topics/tkinter/>`_
  16. The Python Tkinter Topic Guide provides a great deal of information on using Tk
  17. from Python and links to other sources of information on Tk.
  18. `An Introduction to Tkinter <http://www.pythonware.com/library/an-introduction-to-tkinter.htm>`_
  19. Fredrik Lundh's on-line reference material.
  20. `Tkinter reference: a GUI for Python <http://infohost.nmt.edu/tcc/help/pubs/lang.html>`_
  21. On-line reference material.
  22. `Tkinter for JPython <http://jtkinter.sourceforge.net>`_
  23. The Jython interface to Tkinter.
  24. `Python and Tkinter Programming <http://www.amazon.com/exec/obidos/ASIN/1884777813>`_
  25. The book by John Grayson (ISBN 1-884777-81-3).
  26. Tkinter Modules
  27. ---------------
  28. Most of the time, the :mod:`Tkinter` module is all you really need, but a number
  29. of additional modules are available as well. The Tk interface is located in a
  30. binary module named :mod:`_tkinter`. This module contains the low-level
  31. interface to Tk, and should never be used directly by application programmers.
  32. It is usually a shared library (or DLL), but might in some cases be statically
  33. linked with the Python interpreter.
  34. In addition to the Tk interface module, :mod:`Tkinter` includes a number of
  35. Python modules. The two most important modules are the :mod:`Tkinter` module
  36. itself, and a module called :mod:`Tkconstants`. The former automatically imports
  37. the latter, so to use Tkinter, all you need to do is to import one module::
  38. import Tkinter
  39. Or, more often::
  40. from Tkinter import *
  41. .. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)
  42. The :class:`Tk` class is instantiated without arguments. This creates a toplevel
  43. widget of Tk which usually is the main window of an application. Each instance
  44. has its own associated Tcl interpreter.
  45. .. FIXME: The following keyword arguments are currently recognized:
  46. .. versionchanged:: 2.4
  47. The *useTk* parameter was added.
  48. .. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)
  49. The :func:`Tcl` function is a factory function which creates an object much like
  50. that created by the :class:`Tk` class, except that it does not initialize the Tk
  51. subsystem. This is most often useful when driving the Tcl interpreter in an
  52. environment where one doesn't want to create extraneous toplevel windows, or
  53. where one cannot (such as Unix/Linux systems without an X server). An object
  54. created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
  55. subsystem initialized) by calling its :meth:`loadtk` method.
  56. .. versionadded:: 2.4
  57. Other modules that provide Tk support include:
  58. :mod:`ScrolledText`
  59. Text widget with a vertical scroll bar built in.
  60. :mod:`tkColorChooser`
  61. Dialog to let the user choose a color.
  62. :mod:`tkCommonDialog`
  63. Base class for the dialogs defined in the other modules listed here.
  64. :mod:`tkFileDialog`
  65. Common dialogs to allow the user to specify a file to open or save.
  66. :mod:`tkFont`
  67. Utilities to help work with fonts.
  68. :mod:`tkMessageBox`
  69. Access to standard Tk dialog boxes.
  70. :mod:`tkSimpleDialog`
  71. Basic dialogs and convenience functions.
  72. :mod:`Tkdnd`
  73. Drag-and-drop support for :mod:`Tkinter`. This is experimental and should become
  74. deprecated when it is replaced with the Tk DND.
  75. :mod:`turtle`
  76. Turtle graphics in a Tk window.
  77. These have been renamed as well in Python 3.0; they were all made submodules of
  78. the new ``tkinter`` package.
  79. Tkinter Life Preserver
  80. ----------------------
  81. .. sectionauthor:: Matt Conway
  82. This section is not designed to be an exhaustive tutorial on either Tk or
  83. Tkinter. Rather, it is intended as a stop gap, providing some introductory
  84. orientation on the system.
  85. Credits:
  86. * Tkinter was written by Steen Lumholt and Guido van Rossum.
  87. * Tk was written by John Ousterhout while at Berkeley.
  88. * This Life Preserver was written by Matt Conway at the University of Virginia.
  89. * The html rendering, and some liberal editing, was produced from a FrameMaker
  90. version by Ken Manheimer.
  91. * Fredrik Lundh elaborated and revised the class interface descriptions, to get
  92. them current with Tk 4.2.
  93. * Mike Clarkson converted the documentation to LaTeX, and compiled the User
  94. Interface chapter of the reference manual.
  95. How To Use This Section
  96. ^^^^^^^^^^^^^^^^^^^^^^^
  97. This section is designed in two parts: the first half (roughly) covers
  98. background material, while the second half can be taken to the keyboard as a
  99. handy reference.
  100. When trying to answer questions of the form "how do I do blah", it is often best
  101. to find out how to do"blah" in straight Tk, and then convert this back into the
  102. corresponding :mod:`Tkinter` call. Python programmers can often guess at the
  103. correct Python command by looking at the Tk documentation. This means that in
  104. order to use Tkinter, you will have to know a little bit about Tk. This document
  105. can't fulfill that role, so the best we can do is point you to the best
  106. documentation that exists. Here are some hints:
  107. * The authors strongly suggest getting a copy of the Tk man pages. Specifically,
  108. the man pages in the ``mann`` directory are most useful. The ``man3`` man pages
  109. describe the C interface to the Tk library and thus are not especially helpful
  110. for script writers.
  111. * Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
  112. Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
  113. the novice. The book is not exhaustive, and for many details it defers to the
  114. man pages.
  115. * :file:`Tkinter.py` is a last resort for most, but can be a good place to go
  116. when nothing else makes sense.
  117. .. seealso::
  118. `ActiveState Tcl Home Page <http://tcl.activestate.com/>`_
  119. The Tk/Tcl development is largely taking place at ActiveState.
  120. `Tcl and the Tk Toolkit <http://www.amazon.com/exec/obidos/ASIN/020163337X>`_
  121. The book by John Ousterhout, the inventor of Tcl .
  122. `Practical Programming in Tcl and Tk <http://www.amazon.com/exec/obidos/ASIN/0130220280>`_
  123. Brent Welch's encyclopedic book.
  124. A Simple Hello World Program
  125. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  126. ::
  127. from Tkinter import *
  128. class Application(Frame):
  129. def say_hi(self):
  130. print "hi there, everyone!"
  131. def createWidgets(self):
  132. self.QUIT = Button(self)
  133. self.QUIT["text"] = "QUIT"
  134. self.QUIT["fg"] = "red"
  135. self.QUIT["command"] = self.quit
  136. self.QUIT.pack({"side": "left"})
  137. self.hi_there = Button(self)
  138. self.hi_there["text"] = "Hello",
  139. self.hi_there["command"] = self.say_hi
  140. self.hi_there.pack({"side": "left"})
  141. def __init__(self, master=None):
  142. Frame.__init__(self, master)
  143. self.pack()
  144. self.createWidgets()
  145. root = Tk()
  146. app = Application(master=root)
  147. app.mainloop()
  148. root.destroy()
  149. A (Very) Quick Look at Tcl/Tk
  150. -----------------------------
  151. The class hierarchy looks complicated, but in actual practice, application
  152. programmers almost always refer to the classes at the very bottom of the
  153. hierarchy.
  154. Notes:
  155. * These classes are provided for the purposes of organizing certain functions
  156. under one namespace. They aren't meant to be instantiated independently.
  157. * The :class:`Tk` class is meant to be instantiated only once in an application.
  158. Application programmers need not instantiate one explicitly, the system creates
  159. one whenever any of the other classes are instantiated.
  160. * The :class:`Widget` class is not meant to be instantiated, it is meant only
  161. for subclassing to make "real" widgets (in C++, this is called an 'abstract
  162. class').
  163. To make use of this reference material, there will be times when you will need
  164. to know how to read short passages of Tk and how to identify the various parts
  165. of a Tk command. (See section :ref:`tkinter-basic-mapping` for the
  166. :mod:`Tkinter` equivalents of what's below.)
  167. Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just lists
  168. of tokens separated by spaces. A Tk widget is just its *class*, the *options*
  169. that help configure it, and the *actions* that make it do useful things.
  170. To make a widget in Tk, the command is always of the form::
  171. classCommand newPathname options
  172. *classCommand*
  173. denotes which kind of widget to make (a button, a label, a menu...)
  174. *newPathname*
  175. is the new name for this widget. All names in Tk must be unique. To help
  176. enforce this, widgets in Tk are named with *pathnames*, just like files in a
  177. file system. The top level widget, the *root*, is called ``.`` (period) and
  178. children are delimited by more periods. For example,
  179. ``.myApp.controlPanel.okButton`` might be the name of a widget.
  180. *options*
  181. configure the widget's appearance and in some cases, its behavior. The options
  182. come in the form of a list of flags and values. Flags are preceded by a '-',
  183. like Unix shell command flags, and values are put in quotes if they are more
  184. than one word.
  185. For example::
  186. button .fred -fg red -text "hi there"
  187. ^ ^ \_____________________/
  188. | | |
  189. class new options
  190. command widget (-opt val -opt val ...)
  191. Once created, the pathname to the widget becomes a new command. This new
  192. *widget command* is the programmer's handle for getting the new widget to
  193. perform some *action*. In C, you'd express this as someAction(fred,
  194. someOptions), in C++, you would express this as fred.someAction(someOptions),
  195. and in Tk, you say::
  196. .fred someAction someOptions
  197. Note that the object name, ``.fred``, starts with a dot.
  198. As you'd expect, the legal values for *someAction* will depend on the widget's
  199. class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
  200. does not work if fred is a label (disabling of labels is not supported in Tk).
  201. The legal values of *someOptions* is action dependent. Some actions, like
  202. ``disable``, require no arguments, others, like a text-entry box's ``delete``
  203. command, would need arguments to specify what range of text to delete.
  204. .. _tkinter-basic-mapping:
  205. Mapping Basic Tk into Tkinter
  206. -----------------------------
  207. Class commands in Tk correspond to class constructors in Tkinter. ::
  208. button .fred =====> fred = Button()
  209. The master of an object is implicit in the new name given to it at creation
  210. time. In Tkinter, masters are specified explicitly. ::
  211. button .panel.fred =====> fred = Button(panel)
  212. The configuration options in Tk are given in lists of hyphened tags followed by
  213. values. In Tkinter, options are specified as keyword-arguments in the instance
  214. constructor, and keyword-args for configure calls or as instance indices, in
  215. dictionary style, for established instances. See section
  216. :ref:`tkinter-setting-options` on setting options. ::
  217. button .fred -fg red =====> fred = Button(panel, fg = "red")
  218. .fred configure -fg red =====> fred["fg"] = red
  219. OR ==> fred.config(fg = "red")
  220. In Tk, to perform an action on a widget, use the widget name as a command, and
  221. follow it with an action name, possibly with arguments (options). In Tkinter,
  222. you call methods on the class instance to invoke actions on the widget. The
  223. actions (methods) that a given widget can perform are listed in the Tkinter.py
  224. module. ::
  225. .fred invoke =====> fred.invoke()
  226. To give a widget to the packer (geometry manager), you call pack with optional
  227. arguments. In Tkinter, the Pack class holds all this functionality, and the
  228. various forms of the pack command are implemented as methods. All widgets in
  229. :mod:`Tkinter` are subclassed from the Packer, and so inherit all the packing
  230. methods. See the :mod:`Tix` module documentation for additional information on
  231. the Form geometry manager. ::
  232. pack .fred -side left =====> fred.pack(side = "left")
  233. How Tk and Tkinter are Related
  234. ------------------------------
  235. From the top down:
  236. Your App Here (Python)
  237. A Python application makes a :mod:`Tkinter` call.
  238. Tkinter (Python Module)
  239. This call (say, for example, creating a button widget), is implemented in the
  240. *Tkinter* module, which is written in Python. This Python function will parse
  241. the commands and the arguments and convert them into a form that makes them look
  242. as if they had come from a Tk script instead of a Python script.
  243. tkinter (C)
  244. These commands and their arguments will be passed to a C function in the
  245. *tkinter* - note the lowercase - extension module.
  246. Tk Widgets (C and Tcl)
  247. This C function is able to make calls into other C modules, including the C
  248. functions that make up the Tk library. Tk is implemented in C and some Tcl.
  249. The Tcl part of the Tk widgets is used to bind certain default behaviors to
  250. widgets, and is executed once at the point where the Python :mod:`Tkinter`
  251. module is imported. (The user never sees this stage).
  252. Tk (C)
  253. The Tk part of the Tk Widgets implement the final mapping to ...
  254. Xlib (C)
  255. the Xlib library to draw graphics on the screen.
  256. Handy Reference
  257. ---------------
  258. .. _tkinter-setting-options:
  259. Setting Options
  260. ^^^^^^^^^^^^^^^
  261. Options control things like the color and border width of a widget. Options can
  262. be set in three ways:
  263. At object creation time, using keyword arguments
  264. ::
  265. fred = Button(self, fg = "red", bg = "blue")
  266. After object creation, treating the option name like a dictionary index
  267. ::
  268. fred["fg"] = "red"
  269. fred["bg"] = "blue"
  270. Use the config() method to update multiple attrs subsequent to object creation
  271. ::
  272. fred.config(fg = "red", bg = "blue")
  273. For a complete explanation of a given option and its behavior, see the Tk man
  274. pages for the widget in question.
  275. Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
  276. for each widget. The former is a list of options that are common to many
  277. widgets, the latter are the options that are idiosyncratic to that particular
  278. widget. The Standard Options are documented on the :manpage:`options(3)` man
  279. page.
  280. No distinction between standard and widget-specific options is made in this
  281. document. Some options don't apply to some kinds of widgets. Whether a given
  282. widget responds to a particular option depends on the class of the widget;
  283. buttons have a ``command`` option, labels do not.
  284. The options supported by a given widget are listed in that widget's man page, or
  285. can be queried at runtime by calling the :meth:`config` method without
  286. arguments, or by calling the :meth:`keys` method on that widget. The return
  287. value of these calls is a dictionary whose key is the name of the option as a
  288. string (for example, ``'relief'``) and whose values are 5-tuples.
  289. Some options, like ``bg`` are synonyms for common options with long names
  290. (``bg`` is shorthand for "background"). Passing the ``config()`` method the name
  291. of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
  292. back will contain the name of the synonym and the "real" option (such as
  293. ``('bg', 'background')``).
  294. +-------+---------------------------------+--------------+
  295. | Index | Meaning | Example |
  296. +=======+=================================+==============+
  297. | 0 | option name | ``'relief'`` |
  298. +-------+---------------------------------+--------------+
  299. | 1 | option name for database lookup | ``'relief'`` |
  300. +-------+---------------------------------+--------------+
  301. | 2 | option class for database | ``'Relief'`` |
  302. | | lookup | |
  303. +-------+---------------------------------+--------------+
  304. | 3 | default value | ``'raised'`` |
  305. +-------+---------------------------------+--------------+
  306. | 4 | current value | ``'groove'`` |
  307. +-------+---------------------------------+--------------+
  308. Example::
  309. >>> print fred.config()
  310. {'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')}
  311. Of course, the dictionary printed will include all the options available and
  312. their values. This is meant only as an example.
  313. The Packer
  314. ^^^^^^^^^^
  315. .. index:: single: packing (widgets)
  316. The packer is one of Tk's geometry-management mechanisms. Geometry managers
  317. are used to specify the relative positioning of the positioning of widgets
  318. within their container - their mutual *master*. In contrast to the more
  319. cumbersome *placer* (which is used less commonly, and we do not cover here), the
  320. packer takes qualitative relationship specification - *above*, *to the left of*,
  321. *filling*, etc - and works everything out to determine the exact placement
  322. coordinates for you.
  323. The size of any *master* widget is determined by the size of the "slave widgets"
  324. inside. The packer is used to control where slave widgets appear inside the
  325. master into which they are packed. You can pack widgets into frames, and frames
  326. into other frames, in order to achieve the kind of layout you desire.
  327. Additionally, the arrangement is dynamically adjusted to accommodate incremental
  328. changes to the configuration, once it is packed.
  329. Note that widgets do not appear until they have had their geometry specified
  330. with a geometry manager. It's a common early mistake to leave out the geometry
  331. specification, and then be surprised when the widget is created but nothing
  332. appears. A widget will appear only after it has had, for example, the packer's
  333. :meth:`pack` method applied to it.
  334. The pack() method can be called with keyword-option/value pairs that control
  335. where the widget is to appear within its container, and how it is to behave when
  336. the main application window is resized. Here are some examples::
  337. fred.pack() # defaults to side = "top"
  338. fred.pack(side = "left")
  339. fred.pack(expand = 1)
  340. Packer Options
  341. ^^^^^^^^^^^^^^
  342. For more extensive information on the packer and the options that it can take,
  343. see the man pages and page 183 of John Ousterhout's book.
  344. anchor
  345. Anchor type. Denotes where the packer is to place each slave in its parcel.
  346. expand
  347. Boolean, ``0`` or ``1``.
  348. fill
  349. Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.
  350. ipadx and ipady
  351. A distance - designating internal padding on each side of the slave widget.
  352. padx and pady
  353. A distance - designating external padding on each side of the slave widget.
  354. side
  355. Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.
  356. Coupling Widget Variables
  357. ^^^^^^^^^^^^^^^^^^^^^^^^^
  358. The current-value setting of some widgets (like text entry widgets) can be
  359. connected directly to application variables by using special options. These
  360. options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
  361. ``value``. This connection works both ways: if the variable changes for any
  362. reason, the widget it's connected to will be updated to reflect the new value.
  363. Unfortunately, in the current implementation of :mod:`Tkinter` it is not
  364. possible to hand over an arbitrary Python variable to a widget through a
  365. ``variable`` or ``textvariable`` option. The only kinds of variables for which
  366. this works are variables that are subclassed from a class called Variable,
  367. defined in the :mod:`Tkinter` module.
  368. There are many useful subclasses of Variable already defined:
  369. :class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
  370. :class:`BooleanVar`. To read the current value of such a variable, call the
  371. :meth:`get` method on it, and to change its value you call the :meth:`set`
  372. method. If you follow this protocol, the widget will always track the value of
  373. the variable, with no further intervention on your part.
  374. For example::
  375. class App(Frame):
  376. def __init__(self, master=None):
  377. Frame.__init__(self, master)
  378. self.pack()
  379. self.entrythingy = Entry()
  380. self.entrythingy.pack()
  381. # here is the application variable
  382. self.contents = StringVar()
  383. # set it to some value
  384. self.contents.set("this is a variable")
  385. # tell the entry widget to watch this variable
  386. self.entrythingy["textvariable"] = self.contents
  387. # and here we get a callback when the user hits return.
  388. # we will have the program print out the value of the
  389. # application variable when the user hits return
  390. self.entrythingy.bind('<Key-Return>',
  391. self.print_contents)
  392. def print_contents(self, event):
  393. print "hi. contents of entry is now ---->", \
  394. self.contents.get()
  395. The Window Manager
  396. ^^^^^^^^^^^^^^^^^^
  397. .. index:: single: window manager (widgets)
  398. In Tk, there is a utility command, ``wm``, for interacting with the window
  399. manager. Options to the ``wm`` command allow you to control things like titles,
  400. placement, icon bitmaps, and the like. In :mod:`Tkinter`, these commands have
  401. been implemented as methods on the :class:`Wm` class. Toplevel widgets are
  402. subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
  403. directly.
  404. To get at the toplevel window that contains a given widget, you can often just
  405. refer to the widget's master. Of course if the widget has been packed inside of
  406. a frame, the master won't represent a toplevel window. To get at the toplevel
  407. window that contains an arbitrary widget, you can call the :meth:`_root` method.
  408. This method begins with an underscore to denote the fact that this function is
  409. part of the implementation, and not an interface to Tk functionality.
  410. Here are some examples of typical usage::
  411. from Tkinter import *
  412. class App(Frame):
  413. def __init__(self, master=None):
  414. Frame.__init__(self, master)
  415. self.pack()
  416. # create the application
  417. myapp = App()
  418. #
  419. # here are method calls to the window manager class
  420. #
  421. myapp.master.title("My Do-Nothing Application")
  422. myapp.master.maxsize(1000, 400)
  423. # start the program
  424. myapp.mainloop()
  425. Tk Option Data Types
  426. ^^^^^^^^^^^^^^^^^^^^
  427. .. index:: single: Tk Option Data Types
  428. anchor
  429. Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
  430. ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.
  431. bitmap
  432. There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
  433. ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
  434. ``'warning'``. To specify an X bitmap filename, give the full path to the file,
  435. preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.
  436. boolean
  437. You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"`` .
  438. callback
  439. This is any Python function that takes no arguments. For example::
  440. def print_it():
  441. print "hi there"
  442. fred["command"] = print_it
  443. color
  444. Colors can be given as the names of X colors in the rgb.txt file, or as strings
  445. representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
  446. ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
  447. represent any legal hex digit. See page 160 of Ousterhout's book for details.
  448. cursor
  449. The standard X cursor names from :file:`cursorfont.h` can be used, without the
  450. ``XC_`` prefix. For example to get a hand cursor (:const:`XC_hand2`), use the
  451. string ``"hand2"``. You can also specify a bitmap and mask file of your own.
  452. See page 179 of Ousterhout's book.
  453. distance
  454. Screen distances can be specified in either pixels or absolute distances.
  455. Pixels are given as numbers and absolute distances as strings, with the trailing
  456. character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
  457. millimetres, ``p`` for printer's points. For example, 3.5 inches is expressed
  458. as ``"3.5i"``.
  459. font
  460. Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
  461. positive numbers are measured in points; sizes with negative numbers are
  462. measured in pixels.
  463. geometry
  464. This is a string of the form ``widthxheight``, where width and height are
  465. measured in pixels for most widgets (in characters for widgets displaying text).
  466. For example: ``fred["geometry"] = "200x100"``.
  467. justify
  468. Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
  469. ``"fill"``.
  470. region
  471. This is a string with four space-delimited elements, each of which is a legal
  472. distance (see above). For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
  473. ``"3c 2c 4c 10.43c"`` are all legal regions.
  474. relief
  475. Determines what the border style of a widget will be. Legal values are:
  476. ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.
  477. scrollcommand
  478. This is almost always the :meth:`set` method of some scrollbar widget, but can
  479. be any widget method that takes a single argument. Refer to the file
  480. :file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
  481. distribution for an example.
  482. wrap:
  483. Must be one of: ``"none"``, ``"char"``, or ``"word"``.
  484. Bindings and Events
  485. ^^^^^^^^^^^^^^^^^^^
  486. .. index::
  487. single: bind (widgets)
  488. single: events (widgets)
  489. The bind method from the widget command allows you to watch for certain events
  490. and to have a callback function trigger when that event type occurs. The form
  491. of the bind method is::
  492. def bind(self, sequence, func, add=''):
  493. where:
  494. sequence
  495. is a string that denotes the target kind of event. (See the bind man page and
  496. page 201 of John Ousterhout's book for details).
  497. func
  498. is a Python function, taking one argument, to be invoked when the event occurs.
  499. An Event instance will be passed as the argument. (Functions deployed this way
  500. are commonly known as *callbacks*.)
  501. add
  502. is optional, either ``''`` or ``'+'``. Passing an empty string denotes that
  503. this binding is to replace any other bindings that this event is associated
  504. with. Passing a ``'+'`` means that this function is to be added to the list
  505. of functions bound to this event type.
  506. For example::
  507. def turnRed(self, event):
  508. event.widget["activeforeground"] = "red"
  509. self.button.bind("<Enter>", self.turnRed)
  510. Notice how the widget field of the event is being accessed in the
  511. :meth:`turnRed` callback. This field contains the widget that caught the X
  512. event. The following table lists the other event fields you can access, and how
  513. they are denoted in Tk, which can be useful when referring to the Tk man pages.
  514. ::
  515. Tk Tkinter Event Field Tk Tkinter Event Field
  516. -- ------------------- -- -------------------
  517. %f focus %A char
  518. %h height %E send_event
  519. %k keycode %K keysym
  520. %s state %N keysym_num
  521. %t time %T type
  522. %w width %W widget
  523. %x x %X x_root
  524. %y y %Y y_root
  525. The index Parameter
  526. ^^^^^^^^^^^^^^^^^^^
  527. A number of widgets require"index" parameters to be passed. These are used to
  528. point at a specific place in a Text widget, or to particular characters in an
  529. Entry widget, or to particular menu items in a Menu widget.
  530. Entry widget indexes (index, view index, etc.)
  531. Entry widgets have options that refer to character positions in the text being
  532. displayed. You can use these :mod:`Tkinter` functions to access these special
  533. points in text widgets:
  534. AtEnd()
  535. refers to the last position in the text
  536. AtInsert()
  537. refers to the point where the text cursor is
  538. AtSelFirst()
  539. indicates the beginning point of the selected text
  540. AtSelLast()
  541. denotes the last point of the selected text and finally
  542. At(x[, y])
  543. refers to the character at pixel location *x*, *y* (with *y* not used in the
  544. case of a text entry widget, which contains a single line of text).
  545. Text widget indexes
  546. The index notation for Text widgets is very rich and is best described in the Tk
  547. man pages.
  548. Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
  549. Some options and methods for menus manipulate specific menu entries. Anytime a
  550. menu index is needed for an option or a parameter, you may pass in:
  551. * an integer which refers to the numeric position of the entry in the widget,
  552. counted from the top, starting with 0;
  553. * the string ``'active'``, which refers to the menu position that is currently
  554. under the cursor;
  555. * the string ``"last"`` which refers to the last menu item;
  556. * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
  557. as a y pixel coordinate in the menu's coordinate system;
  558. * the string ``"none"``, which indicates no menu entry at all, most often used
  559. with menu.activate() to deactivate all entries, and finally,
  560. * a text string that is pattern matched against the label of the menu entry, as
  561. scanned from the top of the menu to the bottom. Note that this index type is
  562. considered after all the others, which means that matches for menu items
  563. labelled ``last``, ``active``, or ``none`` may be interpreted as the above
  564. literals, instead.
  565. Images
  566. ^^^^^^
  567. Bitmap/Pixelmap images can be created through the subclasses of
  568. :class:`Tkinter.Image`:
  569. * :class:`BitmapImage` can be used for X11 bitmap data.
  570. * :class:`PhotoImage` can be used for GIF and PPM/PGM color bitmaps.
  571. Either type of image is created through either the ``file`` or the ``data``
  572. option (other options are available as well).
  573. The image object can then be used wherever an ``image`` option is supported by
  574. some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
  575. reference to the image. When the last Python reference to the image object is
  576. deleted, the image data is deleted as well, and Tk will display an empty box
  577. wherever the image was used.