/Lib/lib-tk/Tkinter.py

http://unladen-swallow.googlecode.com/ · Python · 3774 lines · 3086 code · 86 blank · 602 comment · 199 complexity · 77f6245e4d47ba42fe974c0a4dbee464 MD5 · raw file

Large files are truncated click here to view the full file

  1. """Wrapper functions for Tcl/Tk.
  2. Tkinter provides classes which allow the display, positioning and
  3. control of widgets. Toplevel widgets are Tk and Toplevel. Other
  4. widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
  5. Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
  6. LabelFrame and PanedWindow.
  7. Properties of the widgets are specified with keyword arguments.
  8. Keyword arguments have the same name as the corresponding resource
  9. under Tk.
  10. Widgets are positioned with one of the geometry managers Place, Pack
  11. or Grid. These managers can be called with methods place, pack, grid
  12. available in every Widget.
  13. Actions are bound to events by resources (e.g. keyword argument
  14. command) or with the method bind.
  15. Example (Hello, World):
  16. import Tkinter
  17. from Tkconstants import *
  18. tk = Tkinter.Tk()
  19. frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
  20. frame.pack(fill=BOTH,expand=1)
  21. label = Tkinter.Label(frame, text="Hello, World")
  22. label.pack(fill=X, expand=1)
  23. button = Tkinter.Button(frame,text="Exit",command=tk.destroy)
  24. button.pack(side=BOTTOM)
  25. tk.mainloop()
  26. """
  27. __version__ = "$Revision: 73770 $"
  28. import sys
  29. if sys.platform == "win32":
  30. # Attempt to configure Tcl/Tk without requiring PATH
  31. import FixTk
  32. import _tkinter # If this fails your Python may not be configured for Tk
  33. tkinter = _tkinter # b/w compat for export
  34. TclError = _tkinter.TclError
  35. from types import *
  36. from Tkconstants import *
  37. wantobjects = 1
  38. TkVersion = float(_tkinter.TK_VERSION)
  39. TclVersion = float(_tkinter.TCL_VERSION)
  40. READABLE = _tkinter.READABLE
  41. WRITABLE = _tkinter.WRITABLE
  42. EXCEPTION = _tkinter.EXCEPTION
  43. # These are not always defined, e.g. not on Win32 with Tk 8.0 :-(
  44. try: _tkinter.createfilehandler
  45. except AttributeError: _tkinter.createfilehandler = None
  46. try: _tkinter.deletefilehandler
  47. except AttributeError: _tkinter.deletefilehandler = None
  48. def _flatten(tuple):
  49. """Internal function."""
  50. res = ()
  51. for item in tuple:
  52. if type(item) in (TupleType, ListType):
  53. res = res + _flatten(item)
  54. elif item is not None:
  55. res = res + (item,)
  56. return res
  57. try: _flatten = _tkinter._flatten
  58. except AttributeError: pass
  59. def _cnfmerge(cnfs):
  60. """Internal function."""
  61. if type(cnfs) is DictionaryType:
  62. return cnfs
  63. elif type(cnfs) in (NoneType, StringType):
  64. return cnfs
  65. else:
  66. cnf = {}
  67. for c in _flatten(cnfs):
  68. try:
  69. cnf.update(c)
  70. except (AttributeError, TypeError), msg:
  71. print "_cnfmerge: fallback due to:", msg
  72. for k, v in c.items():
  73. cnf[k] = v
  74. return cnf
  75. try: _cnfmerge = _tkinter._cnfmerge
  76. except AttributeError: pass
  77. class Event:
  78. """Container for the properties of an event.
  79. Instances of this type are generated if one of the following events occurs:
  80. KeyPress, KeyRelease - for keyboard events
  81. ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
  82. Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
  83. Colormap, Gravity, Reparent, Property, Destroy, Activate,
  84. Deactivate - for window events.
  85. If a callback function for one of these events is registered
  86. using bind, bind_all, bind_class, or tag_bind, the callback is
  87. called with an Event as first argument. It will have the
  88. following attributes (in braces are the event types for which
  89. the attribute is valid):
  90. serial - serial number of event
  91. num - mouse button pressed (ButtonPress, ButtonRelease)
  92. focus - whether the window has the focus (Enter, Leave)
  93. height - height of the exposed window (Configure, Expose)
  94. width - width of the exposed window (Configure, Expose)
  95. keycode - keycode of the pressed key (KeyPress, KeyRelease)
  96. state - state of the event as a number (ButtonPress, ButtonRelease,
  97. Enter, KeyPress, KeyRelease,
  98. Leave, Motion)
  99. state - state as a string (Visibility)
  100. time - when the event occurred
  101. x - x-position of the mouse
  102. y - y-position of the mouse
  103. x_root - x-position of the mouse on the screen
  104. (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  105. y_root - y-position of the mouse on the screen
  106. (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  107. char - pressed character (KeyPress, KeyRelease)
  108. send_event - see X/Windows documentation
  109. keysym - keysym of the event as a string (KeyPress, KeyRelease)
  110. keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
  111. type - type of the event as a number
  112. widget - widget in which the event occurred
  113. delta - delta of wheel movement (MouseWheel)
  114. """
  115. pass
  116. _support_default_root = 1
  117. _default_root = None
  118. def NoDefaultRoot():
  119. """Inhibit setting of default root window.
  120. Call this function to inhibit that the first instance of
  121. Tk is used for windows without an explicit parent window.
  122. """
  123. global _support_default_root
  124. _support_default_root = 0
  125. global _default_root
  126. _default_root = None
  127. del _default_root
  128. def _tkerror(err):
  129. """Internal function."""
  130. pass
  131. def _exit(code='0'):
  132. """Internal function. Calling it will throw the exception SystemExit."""
  133. raise SystemExit, code
  134. _varnum = 0
  135. class Variable:
  136. """Class to define value holders for e.g. buttons.
  137. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
  138. that constrain the type of the value returned from get()."""
  139. _default = ""
  140. def __init__(self, master=None, value=None, name=None):
  141. """Construct a variable
  142. MASTER can be given as master widget.
  143. VALUE is an optional value (defaults to "")
  144. NAME is an optional Tcl name (defaults to PY_VARnum).
  145. If NAME matches an existing variable and VALUE is omitted
  146. then the existing value is retained.
  147. """
  148. global _varnum
  149. if not master:
  150. master = _default_root
  151. self._master = master
  152. self._tk = master.tk
  153. if name:
  154. self._name = name
  155. else:
  156. self._name = 'PY_VAR' + repr(_varnum)
  157. _varnum += 1
  158. if value is not None:
  159. self.set(value)
  160. elif not self._tk.call("info", "exists", self._name):
  161. self.set(self._default)
  162. def __del__(self):
  163. """Unset the variable in Tcl."""
  164. self._tk.globalunsetvar(self._name)
  165. def __str__(self):
  166. """Return the name of the variable in Tcl."""
  167. return self._name
  168. def set(self, value):
  169. """Set the variable to VALUE."""
  170. return self._tk.globalsetvar(self._name, value)
  171. def get(self):
  172. """Return value of variable."""
  173. return self._tk.globalgetvar(self._name)
  174. def trace_variable(self, mode, callback):
  175. """Define a trace callback for the variable.
  176. MODE is one of "r", "w", "u" for read, write, undefine.
  177. CALLBACK must be a function which is called when
  178. the variable is read, written or undefined.
  179. Return the name of the callback.
  180. """
  181. cbname = self._master._register(callback)
  182. self._tk.call("trace", "variable", self._name, mode, cbname)
  183. return cbname
  184. trace = trace_variable
  185. def trace_vdelete(self, mode, cbname):
  186. """Delete the trace callback for a variable.
  187. MODE is one of "r", "w", "u" for read, write, undefine.
  188. CBNAME is the name of the callback returned from trace_variable or trace.
  189. """
  190. self._tk.call("trace", "vdelete", self._name, mode, cbname)
  191. self._master.deletecommand(cbname)
  192. def trace_vinfo(self):
  193. """Return all trace callback information."""
  194. return map(self._tk.split, self._tk.splitlist(
  195. self._tk.call("trace", "vinfo", self._name)))
  196. def __eq__(self, other):
  197. """Comparison for equality (==).
  198. Note: if the Variable's master matters to behavior
  199. also compare self._master == other._master
  200. """
  201. return self.__class__.__name__ == other.__class__.__name__ \
  202. and self._name == other._name
  203. class StringVar(Variable):
  204. """Value holder for strings variables."""
  205. _default = ""
  206. def __init__(self, master=None, value=None, name=None):
  207. """Construct a string variable.
  208. MASTER can be given as master widget.
  209. VALUE is an optional value (defaults to "")
  210. NAME is an optional Tcl name (defaults to PY_VARnum).
  211. If NAME matches an existing variable and VALUE is omitted
  212. then the existing value is retained.
  213. """
  214. Variable.__init__(self, master, value, name)
  215. def get(self):
  216. """Return value of variable as string."""
  217. value = self._tk.globalgetvar(self._name)
  218. if isinstance(value, basestring):
  219. return value
  220. return str(value)
  221. class IntVar(Variable):
  222. """Value holder for integer variables."""
  223. _default = 0
  224. def __init__(self, master=None, value=None, name=None):
  225. """Construct an integer variable.
  226. MASTER can be given as master widget.
  227. VALUE is an optional value (defaults to 0)
  228. NAME is an optional Tcl name (defaults to PY_VARnum).
  229. If NAME matches an existing variable and VALUE is omitted
  230. then the existing value is retained.
  231. """
  232. Variable.__init__(self, master, value, name)
  233. def set(self, value):
  234. """Set the variable to value, converting booleans to integers."""
  235. if isinstance(value, bool):
  236. value = int(value)
  237. return Variable.set(self, value)
  238. def get(self):
  239. """Return the value of the variable as an integer."""
  240. return getint(self._tk.globalgetvar(self._name))
  241. class DoubleVar(Variable):
  242. """Value holder for float variables."""
  243. _default = 0.0
  244. def __init__(self, master=None, value=None, name=None):
  245. """Construct a float variable.
  246. MASTER can be given as master widget.
  247. VALUE is an optional value (defaults to 0.0)
  248. NAME is an optional Tcl name (defaults to PY_VARnum).
  249. If NAME matches an existing variable and VALUE is omitted
  250. then the existing value is retained.
  251. """
  252. Variable.__init__(self, master, value, name)
  253. def get(self):
  254. """Return the value of the variable as a float."""
  255. return getdouble(self._tk.globalgetvar(self._name))
  256. class BooleanVar(Variable):
  257. """Value holder for boolean variables."""
  258. _default = False
  259. def __init__(self, master=None, value=None, name=None):
  260. """Construct a boolean variable.
  261. MASTER can be given as master widget.
  262. VALUE is an optional value (defaults to False)
  263. NAME is an optional Tcl name (defaults to PY_VARnum).
  264. If NAME matches an existing variable and VALUE is omitted
  265. then the existing value is retained.
  266. """
  267. Variable.__init__(self, master, value, name)
  268. def get(self):
  269. """Return the value of the variable as a bool."""
  270. return self._tk.getboolean(self._tk.globalgetvar(self._name))
  271. def mainloop(n=0):
  272. """Run the main loop of Tcl."""
  273. _default_root.tk.mainloop(n)
  274. getint = int
  275. getdouble = float
  276. def getboolean(s):
  277. """Convert true and false to integer values 1 and 0."""
  278. return _default_root.tk.getboolean(s)
  279. # Methods defined on both toplevel and interior widgets
  280. class Misc:
  281. """Internal class.
  282. Base class which defines methods common for interior widgets."""
  283. # XXX font command?
  284. _tclCommands = None
  285. def destroy(self):
  286. """Internal function.
  287. Delete all Tcl commands created for
  288. this widget in the Tcl interpreter."""
  289. if self._tclCommands is not None:
  290. for name in self._tclCommands:
  291. #print '- Tkinter: deleted command', name
  292. self.tk.deletecommand(name)
  293. self._tclCommands = None
  294. def deletecommand(self, name):
  295. """Internal function.
  296. Delete the Tcl command provided in NAME."""
  297. #print '- Tkinter: deleted command', name
  298. self.tk.deletecommand(name)
  299. try:
  300. self._tclCommands.remove(name)
  301. except ValueError:
  302. pass
  303. def tk_strictMotif(self, boolean=None):
  304. """Set Tcl internal variable, whether the look and feel
  305. should adhere to Motif.
  306. A parameter of 1 means adhere to Motif (e.g. no color
  307. change if mouse passes over slider).
  308. Returns the set value."""
  309. return self.tk.getboolean(self.tk.call(
  310. 'set', 'tk_strictMotif', boolean))
  311. def tk_bisque(self):
  312. """Change the color scheme to light brown as used in Tk 3.6 and before."""
  313. self.tk.call('tk_bisque')
  314. def tk_setPalette(self, *args, **kw):
  315. """Set a new color scheme for all widget elements.
  316. A single color as argument will cause that all colors of Tk
  317. widget elements are derived from this.
  318. Alternatively several keyword parameters and its associated
  319. colors can be given. The following keywords are valid:
  320. activeBackground, foreground, selectColor,
  321. activeForeground, highlightBackground, selectBackground,
  322. background, highlightColor, selectForeground,
  323. disabledForeground, insertBackground, troughColor."""
  324. self.tk.call(('tk_setPalette',)
  325. + _flatten(args) + _flatten(kw.items()))
  326. def tk_menuBar(self, *args):
  327. """Do not use. Needed in Tk 3.6 and earlier."""
  328. pass # obsolete since Tk 4.0
  329. def wait_variable(self, name='PY_VAR'):
  330. """Wait until the variable is modified.
  331. A parameter of type IntVar, StringVar, DoubleVar or
  332. BooleanVar must be given."""
  333. self.tk.call('tkwait', 'variable', name)
  334. waitvar = wait_variable # XXX b/w compat
  335. def wait_window(self, window=None):
  336. """Wait until a WIDGET is destroyed.
  337. If no parameter is given self is used."""
  338. if window is None:
  339. window = self
  340. self.tk.call('tkwait', 'window', window._w)
  341. def wait_visibility(self, window=None):
  342. """Wait until the visibility of a WIDGET changes
  343. (e.g. it appears).
  344. If no parameter is given self is used."""
  345. if window is None:
  346. window = self
  347. self.tk.call('tkwait', 'visibility', window._w)
  348. def setvar(self, name='PY_VAR', value='1'):
  349. """Set Tcl variable NAME to VALUE."""
  350. self.tk.setvar(name, value)
  351. def getvar(self, name='PY_VAR'):
  352. """Return value of Tcl variable NAME."""
  353. return self.tk.getvar(name)
  354. getint = int
  355. getdouble = float
  356. def getboolean(self, s):
  357. """Return a boolean value for Tcl boolean values true and false given as parameter."""
  358. return self.tk.getboolean(s)
  359. def focus_set(self):
  360. """Direct input focus to this widget.
  361. If the application currently does not have the focus
  362. this widget will get the focus if the application gets
  363. the focus through the window manager."""
  364. self.tk.call('focus', self._w)
  365. focus = focus_set # XXX b/w compat?
  366. def focus_force(self):
  367. """Direct input focus to this widget even if the
  368. application does not have the focus. Use with
  369. caution!"""
  370. self.tk.call('focus', '-force', self._w)
  371. def focus_get(self):
  372. """Return the widget which has currently the focus in the
  373. application.
  374. Use focus_displayof to allow working with several
  375. displays. Return None if application does not have
  376. the focus."""
  377. name = self.tk.call('focus')
  378. if name == 'none' or not name: return None
  379. return self._nametowidget(name)
  380. def focus_displayof(self):
  381. """Return the widget which has currently the focus on the
  382. display where this widget is located.
  383. Return None if the application does not have the focus."""
  384. name = self.tk.call('focus', '-displayof', self._w)
  385. if name == 'none' or not name: return None
  386. return self._nametowidget(name)
  387. def focus_lastfor(self):
  388. """Return the widget which would have the focus if top level
  389. for this widget gets the focus from the window manager."""
  390. name = self.tk.call('focus', '-lastfor', self._w)
  391. if name == 'none' or not name: return None
  392. return self._nametowidget(name)
  393. def tk_focusFollowsMouse(self):
  394. """The widget under mouse will get automatically focus. Can not
  395. be disabled easily."""
  396. self.tk.call('tk_focusFollowsMouse')
  397. def tk_focusNext(self):
  398. """Return the next widget in the focus order which follows
  399. widget which has currently the focus.
  400. The focus order first goes to the next child, then to
  401. the children of the child recursively and then to the
  402. next sibling which is higher in the stacking order. A
  403. widget is omitted if it has the takefocus resource set
  404. to 0."""
  405. name = self.tk.call('tk_focusNext', self._w)
  406. if not name: return None
  407. return self._nametowidget(name)
  408. def tk_focusPrev(self):
  409. """Return previous widget in the focus order. See tk_focusNext for details."""
  410. name = self.tk.call('tk_focusPrev', self._w)
  411. if not name: return None
  412. return self._nametowidget(name)
  413. def after(self, ms, func=None, *args):
  414. """Call function once after given time.
  415. MS specifies the time in milliseconds. FUNC gives the
  416. function which shall be called. Additional parameters
  417. are given as parameters to the function call. Return
  418. identifier to cancel scheduling with after_cancel."""
  419. if not func:
  420. # I'd rather use time.sleep(ms*0.001)
  421. self.tk.call('after', ms)
  422. else:
  423. def callit():
  424. try:
  425. func(*args)
  426. finally:
  427. try:
  428. self.deletecommand(name)
  429. except TclError:
  430. pass
  431. name = self._register(callit)
  432. return self.tk.call('after', ms, name)
  433. def after_idle(self, func, *args):
  434. """Call FUNC once if the Tcl main loop has no event to
  435. process.
  436. Return an identifier to cancel the scheduling with
  437. after_cancel."""
  438. return self.after('idle', func, *args)
  439. def after_cancel(self, id):
  440. """Cancel scheduling of function identified with ID.
  441. Identifier returned by after or after_idle must be
  442. given as first parameter."""
  443. try:
  444. data = self.tk.call('after', 'info', id)
  445. # In Tk 8.3, splitlist returns: (script, type)
  446. # In Tk 8.4, splitlist may return (script, type) or (script,)
  447. script = self.tk.splitlist(data)[0]
  448. self.deletecommand(script)
  449. except TclError:
  450. pass
  451. self.tk.call('after', 'cancel', id)
  452. def bell(self, displayof=0):
  453. """Ring a display's bell."""
  454. self.tk.call(('bell',) + self._displayof(displayof))
  455. # Clipboard handling:
  456. def clipboard_get(self, **kw):
  457. """Retrieve data from the clipboard on window's display.
  458. The window keyword defaults to the root window of the Tkinter
  459. application.
  460. The type keyword specifies the form in which the data is
  461. to be returned and should be an atom name such as STRING
  462. or FILE_NAME. Type defaults to STRING.
  463. This command is equivalent to:
  464. selection_get(CLIPBOARD)
  465. """
  466. return self.tk.call(('clipboard', 'get') + self._options(kw))
  467. def clipboard_clear(self, **kw):
  468. """Clear the data in the Tk clipboard.
  469. A widget specified for the optional displayof keyword
  470. argument specifies the target display."""
  471. if not kw.has_key('displayof'): kw['displayof'] = self._w
  472. self.tk.call(('clipboard', 'clear') + self._options(kw))
  473. def clipboard_append(self, string, **kw):
  474. """Append STRING to the Tk clipboard.
  475. A widget specified at the optional displayof keyword
  476. argument specifies the target display. The clipboard
  477. can be retrieved with selection_get."""
  478. if not kw.has_key('displayof'): kw['displayof'] = self._w
  479. self.tk.call(('clipboard', 'append') + self._options(kw)
  480. + ('--', string))
  481. # XXX grab current w/o window argument
  482. def grab_current(self):
  483. """Return widget which has currently the grab in this application
  484. or None."""
  485. name = self.tk.call('grab', 'current', self._w)
  486. if not name: return None
  487. return self._nametowidget(name)
  488. def grab_release(self):
  489. """Release grab for this widget if currently set."""
  490. self.tk.call('grab', 'release', self._w)
  491. def grab_set(self):
  492. """Set grab for this widget.
  493. A grab directs all events to this and descendant
  494. widgets in the application."""
  495. self.tk.call('grab', 'set', self._w)
  496. def grab_set_global(self):
  497. """Set global grab for this widget.
  498. A global grab directs all events to this and
  499. descendant widgets on the display. Use with caution -
  500. other applications do not get events anymore."""
  501. self.tk.call('grab', 'set', '-global', self._w)
  502. def grab_status(self):
  503. """Return None, "local" or "global" if this widget has
  504. no, a local or a global grab."""
  505. status = self.tk.call('grab', 'status', self._w)
  506. if status == 'none': status = None
  507. return status
  508. def option_add(self, pattern, value, priority = None):
  509. """Set a VALUE (second parameter) for an option
  510. PATTERN (first parameter).
  511. An optional third parameter gives the numeric priority
  512. (defaults to 80)."""
  513. self.tk.call('option', 'add', pattern, value, priority)
  514. def option_clear(self):
  515. """Clear the option database.
  516. It will be reloaded if option_add is called."""
  517. self.tk.call('option', 'clear')
  518. def option_get(self, name, className):
  519. """Return the value for an option NAME for this widget
  520. with CLASSNAME.
  521. Values with higher priority override lower values."""
  522. return self.tk.call('option', 'get', self._w, name, className)
  523. def option_readfile(self, fileName, priority = None):
  524. """Read file FILENAME into the option database.
  525. An optional second parameter gives the numeric
  526. priority."""
  527. self.tk.call('option', 'readfile', fileName, priority)
  528. def selection_clear(self, **kw):
  529. """Clear the current X selection."""
  530. if not kw.has_key('displayof'): kw['displayof'] = self._w
  531. self.tk.call(('selection', 'clear') + self._options(kw))
  532. def selection_get(self, **kw):
  533. """Return the contents of the current X selection.
  534. A keyword parameter selection specifies the name of
  535. the selection and defaults to PRIMARY. A keyword
  536. parameter displayof specifies a widget on the display
  537. to use."""
  538. if not kw.has_key('displayof'): kw['displayof'] = self._w
  539. return self.tk.call(('selection', 'get') + self._options(kw))
  540. def selection_handle(self, command, **kw):
  541. """Specify a function COMMAND to call if the X
  542. selection owned by this widget is queried by another
  543. application.
  544. This function must return the contents of the
  545. selection. The function will be called with the
  546. arguments OFFSET and LENGTH which allows the chunking
  547. of very long selections. The following keyword
  548. parameters can be provided:
  549. selection - name of the selection (default PRIMARY),
  550. type - type of the selection (e.g. STRING, FILE_NAME)."""
  551. name = self._register(command)
  552. self.tk.call(('selection', 'handle') + self._options(kw)
  553. + (self._w, name))
  554. def selection_own(self, **kw):
  555. """Become owner of X selection.
  556. A keyword parameter selection specifies the name of
  557. the selection (default PRIMARY)."""
  558. self.tk.call(('selection', 'own') +
  559. self._options(kw) + (self._w,))
  560. def selection_own_get(self, **kw):
  561. """Return owner of X selection.
  562. The following keyword parameter can
  563. be provided:
  564. selection - name of the selection (default PRIMARY),
  565. type - type of the selection (e.g. STRING, FILE_NAME)."""
  566. if not kw.has_key('displayof'): kw['displayof'] = self._w
  567. name = self.tk.call(('selection', 'own') + self._options(kw))
  568. if not name: return None
  569. return self._nametowidget(name)
  570. def send(self, interp, cmd, *args):
  571. """Send Tcl command CMD to different interpreter INTERP to be executed."""
  572. return self.tk.call(('send', interp, cmd) + args)
  573. def lower(self, belowThis=None):
  574. """Lower this widget in the stacking order."""
  575. self.tk.call('lower', self._w, belowThis)
  576. def tkraise(self, aboveThis=None):
  577. """Raise this widget in the stacking order."""
  578. self.tk.call('raise', self._w, aboveThis)
  579. lift = tkraise
  580. def colormodel(self, value=None):
  581. """Useless. Not implemented in Tk."""
  582. return self.tk.call('tk', 'colormodel', self._w, value)
  583. def winfo_atom(self, name, displayof=0):
  584. """Return integer which represents atom NAME."""
  585. args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  586. return getint(self.tk.call(args))
  587. def winfo_atomname(self, id, displayof=0):
  588. """Return name of atom with identifier ID."""
  589. args = ('winfo', 'atomname') \
  590. + self._displayof(displayof) + (id,)
  591. return self.tk.call(args)
  592. def winfo_cells(self):
  593. """Return number of cells in the colormap for this widget."""
  594. return getint(
  595. self.tk.call('winfo', 'cells', self._w))
  596. def winfo_children(self):
  597. """Return a list of all widgets which are children of this widget."""
  598. result = []
  599. for child in self.tk.splitlist(
  600. self.tk.call('winfo', 'children', self._w)):
  601. try:
  602. # Tcl sometimes returns extra windows, e.g. for
  603. # menus; those need to be skipped
  604. result.append(self._nametowidget(child))
  605. except KeyError:
  606. pass
  607. return result
  608. def winfo_class(self):
  609. """Return window class name of this widget."""
  610. return self.tk.call('winfo', 'class', self._w)
  611. def winfo_colormapfull(self):
  612. """Return true if at the last color request the colormap was full."""
  613. return self.tk.getboolean(
  614. self.tk.call('winfo', 'colormapfull', self._w))
  615. def winfo_containing(self, rootX, rootY, displayof=0):
  616. """Return the widget which is at the root coordinates ROOTX, ROOTY."""
  617. args = ('winfo', 'containing') \
  618. + self._displayof(displayof) + (rootX, rootY)
  619. name = self.tk.call(args)
  620. if not name: return None
  621. return self._nametowidget(name)
  622. def winfo_depth(self):
  623. """Return the number of bits per pixel."""
  624. return getint(self.tk.call('winfo', 'depth', self._w))
  625. def winfo_exists(self):
  626. """Return true if this widget exists."""
  627. return getint(
  628. self.tk.call('winfo', 'exists', self._w))
  629. def winfo_fpixels(self, number):
  630. """Return the number of pixels for the given distance NUMBER
  631. (e.g. "3c") as float."""
  632. return getdouble(self.tk.call(
  633. 'winfo', 'fpixels', self._w, number))
  634. def winfo_geometry(self):
  635. """Return geometry string for this widget in the form "widthxheight+X+Y"."""
  636. return self.tk.call('winfo', 'geometry', self._w)
  637. def winfo_height(self):
  638. """Return height of this widget."""
  639. return getint(
  640. self.tk.call('winfo', 'height', self._w))
  641. def winfo_id(self):
  642. """Return identifier ID for this widget."""
  643. return self.tk.getint(
  644. self.tk.call('winfo', 'id', self._w))
  645. def winfo_interps(self, displayof=0):
  646. """Return the name of all Tcl interpreters for this display."""
  647. args = ('winfo', 'interps') + self._displayof(displayof)
  648. return self.tk.splitlist(self.tk.call(args))
  649. def winfo_ismapped(self):
  650. """Return true if this widget is mapped."""
  651. return getint(
  652. self.tk.call('winfo', 'ismapped', self._w))
  653. def winfo_manager(self):
  654. """Return the window mananger name for this widget."""
  655. return self.tk.call('winfo', 'manager', self._w)
  656. def winfo_name(self):
  657. """Return the name of this widget."""
  658. return self.tk.call('winfo', 'name', self._w)
  659. def winfo_parent(self):
  660. """Return the name of the parent of this widget."""
  661. return self.tk.call('winfo', 'parent', self._w)
  662. def winfo_pathname(self, id, displayof=0):
  663. """Return the pathname of the widget given by ID."""
  664. args = ('winfo', 'pathname') \
  665. + self._displayof(displayof) + (id,)
  666. return self.tk.call(args)
  667. def winfo_pixels(self, number):
  668. """Rounded integer value of winfo_fpixels."""
  669. return getint(
  670. self.tk.call('winfo', 'pixels', self._w, number))
  671. def winfo_pointerx(self):
  672. """Return the x coordinate of the pointer on the root window."""
  673. return getint(
  674. self.tk.call('winfo', 'pointerx', self._w))
  675. def winfo_pointerxy(self):
  676. """Return a tuple of x and y coordinates of the pointer on the root window."""
  677. return self._getints(
  678. self.tk.call('winfo', 'pointerxy', self._w))
  679. def winfo_pointery(self):
  680. """Return the y coordinate of the pointer on the root window."""
  681. return getint(
  682. self.tk.call('winfo', 'pointery', self._w))
  683. def winfo_reqheight(self):
  684. """Return requested height of this widget."""
  685. return getint(
  686. self.tk.call('winfo', 'reqheight', self._w))
  687. def winfo_reqwidth(self):
  688. """Return requested width of this widget."""
  689. return getint(
  690. self.tk.call('winfo', 'reqwidth', self._w))
  691. def winfo_rgb(self, color):
  692. """Return tuple of decimal values for red, green, blue for
  693. COLOR in this widget."""
  694. return self._getints(
  695. self.tk.call('winfo', 'rgb', self._w, color))
  696. def winfo_rootx(self):
  697. """Return x coordinate of upper left corner of this widget on the
  698. root window."""
  699. return getint(
  700. self.tk.call('winfo', 'rootx', self._w))
  701. def winfo_rooty(self):
  702. """Return y coordinate of upper left corner of this widget on the
  703. root window."""
  704. return getint(
  705. self.tk.call('winfo', 'rooty', self._w))
  706. def winfo_screen(self):
  707. """Return the screen name of this widget."""
  708. return self.tk.call('winfo', 'screen', self._w)
  709. def winfo_screencells(self):
  710. """Return the number of the cells in the colormap of the screen
  711. of this widget."""
  712. return getint(
  713. self.tk.call('winfo', 'screencells', self._w))
  714. def winfo_screendepth(self):
  715. """Return the number of bits per pixel of the root window of the
  716. screen of this widget."""
  717. return getint(
  718. self.tk.call('winfo', 'screendepth', self._w))
  719. def winfo_screenheight(self):
  720. """Return the number of pixels of the height of the screen of this widget
  721. in pixel."""
  722. return getint(
  723. self.tk.call('winfo', 'screenheight', self._w))
  724. def winfo_screenmmheight(self):
  725. """Return the number of pixels of the height of the screen of
  726. this widget in mm."""
  727. return getint(
  728. self.tk.call('winfo', 'screenmmheight', self._w))
  729. def winfo_screenmmwidth(self):
  730. """Return the number of pixels of the width of the screen of
  731. this widget in mm."""
  732. return getint(
  733. self.tk.call('winfo', 'screenmmwidth', self._w))
  734. def winfo_screenvisual(self):
  735. """Return one of the strings directcolor, grayscale, pseudocolor,
  736. staticcolor, staticgray, or truecolor for the default
  737. colormodel of this screen."""
  738. return self.tk.call('winfo', 'screenvisual', self._w)
  739. def winfo_screenwidth(self):
  740. """Return the number of pixels of the width of the screen of
  741. this widget in pixel."""
  742. return getint(
  743. self.tk.call('winfo', 'screenwidth', self._w))
  744. def winfo_server(self):
  745. """Return information of the X-Server of the screen of this widget in
  746. the form "XmajorRminor vendor vendorVersion"."""
  747. return self.tk.call('winfo', 'server', self._w)
  748. def winfo_toplevel(self):
  749. """Return the toplevel widget of this widget."""
  750. return self._nametowidget(self.tk.call(
  751. 'winfo', 'toplevel', self._w))
  752. def winfo_viewable(self):
  753. """Return true if the widget and all its higher ancestors are mapped."""
  754. return getint(
  755. self.tk.call('winfo', 'viewable', self._w))
  756. def winfo_visual(self):
  757. """Return one of the strings directcolor, grayscale, pseudocolor,
  758. staticcolor, staticgray, or truecolor for the
  759. colormodel of this widget."""
  760. return self.tk.call('winfo', 'visual', self._w)
  761. def winfo_visualid(self):
  762. """Return the X identifier for the visual for this widget."""
  763. return self.tk.call('winfo', 'visualid', self._w)
  764. def winfo_visualsavailable(self, includeids=0):
  765. """Return a list of all visuals available for the screen
  766. of this widget.
  767. Each item in the list consists of a visual name (see winfo_visual), a
  768. depth and if INCLUDEIDS=1 is given also the X identifier."""
  769. data = self.tk.split(
  770. self.tk.call('winfo', 'visualsavailable', self._w,
  771. includeids and 'includeids' or None))
  772. if type(data) is StringType:
  773. data = [self.tk.split(data)]
  774. return map(self.__winfo_parseitem, data)
  775. def __winfo_parseitem(self, t):
  776. """Internal function."""
  777. return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
  778. def __winfo_getint(self, x):
  779. """Internal function."""
  780. return int(x, 0)
  781. def winfo_vrootheight(self):
  782. """Return the height of the virtual root window associated with this
  783. widget in pixels. If there is no virtual root window return the
  784. height of the screen."""
  785. return getint(
  786. self.tk.call('winfo', 'vrootheight', self._w))
  787. def winfo_vrootwidth(self):
  788. """Return the width of the virtual root window associated with this
  789. widget in pixel. If there is no virtual root window return the
  790. width of the screen."""
  791. return getint(
  792. self.tk.call('winfo', 'vrootwidth', self._w))
  793. def winfo_vrootx(self):
  794. """Return the x offset of the virtual root relative to the root
  795. window of the screen of this widget."""
  796. return getint(
  797. self.tk.call('winfo', 'vrootx', self._w))
  798. def winfo_vrooty(self):
  799. """Return the y offset of the virtual root relative to the root
  800. window of the screen of this widget."""
  801. return getint(
  802. self.tk.call('winfo', 'vrooty', self._w))
  803. def winfo_width(self):
  804. """Return the width of this widget."""
  805. return getint(
  806. self.tk.call('winfo', 'width', self._w))
  807. def winfo_x(self):
  808. """Return the x coordinate of the upper left corner of this widget
  809. in the parent."""
  810. return getint(
  811. self.tk.call('winfo', 'x', self._w))
  812. def winfo_y(self):
  813. """Return the y coordinate of the upper left corner of this widget
  814. in the parent."""
  815. return getint(
  816. self.tk.call('winfo', 'y', self._w))
  817. def update(self):
  818. """Enter event loop until all pending events have been processed by Tcl."""
  819. self.tk.call('update')
  820. def update_idletasks(self):
  821. """Enter event loop until all idle callbacks have been called. This
  822. will update the display of windows but not process events caused by
  823. the user."""
  824. self.tk.call('update', 'idletasks')
  825. def bindtags(self, tagList=None):
  826. """Set or get the list of bindtags for this widget.
  827. With no argument return the list of all bindtags associated with
  828. this widget. With a list of strings as argument the bindtags are
  829. set to this list. The bindtags determine in which order events are
  830. processed (see bind)."""
  831. if tagList is None:
  832. return self.tk.splitlist(
  833. self.tk.call('bindtags', self._w))
  834. else:
  835. self.tk.call('bindtags', self._w, tagList)
  836. def _bind(self, what, sequence, func, add, needcleanup=1):
  837. """Internal function."""
  838. if type(func) is StringType:
  839. self.tk.call(what + (sequence, func))
  840. elif func:
  841. funcid = self._register(func, self._substitute,
  842. needcleanup)
  843. cmd = ('%sif {"[%s %s]" == "break"} break\n'
  844. %
  845. (add and '+' or '',
  846. funcid, self._subst_format_str))
  847. self.tk.call(what + (sequence, cmd))
  848. return funcid
  849. elif sequence:
  850. return self.tk.call(what + (sequence,))
  851. else:
  852. return self.tk.splitlist(self.tk.call(what))
  853. def bind(self, sequence=None, func=None, add=None):
  854. """Bind to this widget at event SEQUENCE a call to function FUNC.
  855. SEQUENCE is a string of concatenated event
  856. patterns. An event pattern is of the form
  857. <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
  858. of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
  859. Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
  860. B3, Alt, Button4, B4, Double, Button5, B5 Triple,
  861. Mod1, M1. TYPE is one of Activate, Enter, Map,
  862. ButtonPress, Button, Expose, Motion, ButtonRelease
  863. FocusIn, MouseWheel, Circulate, FocusOut, Property,
  864. Colormap, Gravity Reparent, Configure, KeyPress, Key,
  865. Unmap, Deactivate, KeyRelease Visibility, Destroy,
  866. Leave and DETAIL is the button number for ButtonPress,
  867. ButtonRelease and DETAIL is the Keysym for KeyPress and
  868. KeyRelease. Examples are
  869. <Control-Button-1> for pressing Control and mouse button 1 or
  870. <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
  871. An event pattern can also be a virtual event of the form
  872. <<AString>> where AString can be arbitrary. This
  873. event can be generated by event_generate.
  874. If events are concatenated they must appear shortly
  875. after each other.
  876. FUNC will be called if the event sequence occurs with an
  877. instance of Event as argument. If the return value of FUNC is
  878. "break" no further bound function is invoked.
  879. An additional boolean parameter ADD specifies whether FUNC will
  880. be called additionally to the other bound function or whether
  881. it will replace the previous function.
  882. Bind will return an identifier to allow deletion of the bound function with
  883. unbind without memory leak.
  884. If FUNC or SEQUENCE is omitted the bound function or list
  885. of bound events are returned."""
  886. return self._bind(('bind', self._w), sequence, func, add)
  887. def unbind(self, sequence, funcid=None):
  888. """Unbind for this widget for event SEQUENCE the
  889. function identified with FUNCID."""
  890. self.tk.call('bind', self._w, sequence, '')
  891. if funcid:
  892. self.deletecommand(funcid)
  893. def bind_all(self, sequence=None, func=None, add=None):
  894. """Bind to all widgets at an event SEQUENCE a call to function FUNC.
  895. An additional boolean parameter ADD specifies whether FUNC will
  896. be called additionally to the other bound function or whether
  897. it will replace the previous function. See bind for the return value."""
  898. return self._bind(('bind', 'all'), sequence, func, add, 0)
  899. def unbind_all(self, sequence):
  900. """Unbind for all widgets for event SEQUENCE all functions."""
  901. self.tk.call('bind', 'all' , sequence, '')
  902. def bind_class(self, className, sequence=None, func=None, add=None):
  903. """Bind to widgets with bindtag CLASSNAME at event
  904. SEQUENCE a call of function FUNC. An additional
  905. boolean parameter ADD specifies whether FUNC will be
  906. called additionally to the other bound function or
  907. whether it will replace the previous function. See bind for
  908. the return value."""
  909. return self._bind(('bind', className), sequence, func, add, 0)
  910. def unbind_class(self, className, sequence):
  911. """Unbind for a all widgets with bindtag CLASSNAME for event SEQUENCE
  912. all functions."""
  913. self.tk.call('bind', className , sequence, '')
  914. def mainloop(self, n=0):
  915. """Call the mainloop of Tk."""
  916. self.tk.mainloop(n)
  917. def quit(self):
  918. """Quit the Tcl interpreter. All widgets will be destroyed."""
  919. self.tk.quit()
  920. def _getints(self, string):
  921. """Internal function."""
  922. if string:
  923. return tuple(map(getint, self.tk.splitlist(string)))
  924. def _getdoubles(self, string):
  925. """Internal function."""
  926. if string:
  927. return tuple(map(getdouble, self.tk.splitlist(string)))
  928. def _getboolean(self, string):
  929. """Internal function."""
  930. if string:
  931. return self.tk.getboolean(string)
  932. def _displayof(self, displayof):
  933. """Internal function."""
  934. if displayof:
  935. return ('-displayof', displayof)
  936. if displayof is None:
  937. return ('-displayof', self._w)
  938. return ()
  939. def _options(self, cnf, kw = None):
  940. """Internal function."""
  941. if kw:
  942. cnf = _cnfmerge((cnf, kw))
  943. else:
  944. cnf = _cnfmerge(cnf)
  945. res = ()
  946. for k, v in cnf.items():
  947. if v is not None:
  948. if k[-1] == '_': k = k[:-1]
  949. if callable(v):
  950. v = self._register(v)
  951. elif isinstance(v, (tuple, list)):
  952. nv = []
  953. for item in v:
  954. if not isinstance(item, (basestring, int)):
  955. break
  956. elif isinstance(item, int):
  957. nv.append('%d' % item)
  958. else:
  959. # format it to proper Tcl code if it contains space
  960. nv.append(('{%s}' if ' ' in item else '%s') % item)
  961. else:
  962. v = ' '.join(nv)
  963. res = res + ('-'+k, v)
  964. return res
  965. def nametowidget(self, name):
  966. """Return the Tkinter instance of a widget identified by
  967. its Tcl name NAME."""
  968. name = str(name).split('.')
  969. w = self
  970. if not name[0]:
  971. w = w._root()
  972. name = name[1:]
  973. for n in name:
  974. if not n:
  975. break
  976. w = w.children[n]
  977. return w
  978. _nametowidget = nametowidget
  979. def _register(self, func, subst=None, needcleanup=1):
  980. """Return a newly created Tcl function. If this
  981. function is called, the Python function FUNC will
  982. be executed. An optional function SUBST can
  983. be given which will be executed before FUNC."""
  984. f = CallWrapper(func, subst, self).__call__
  985. name = repr(id(f))
  986. try:
  987. func = func.im_func
  988. except AttributeError:
  989. pass
  990. try:
  991. name = name + func.__name__
  992. except AttributeError:
  993. pass
  994. self.tk.createcommand(name, f)
  995. if needcleanup:
  996. if self._tclCommands is None:
  997. self._tclCommands = []
  998. self._tclCommands.append(name)
  999. return name
  1000. register = _register
  1001. def _root(self):
  1002. """Internal function."""
  1003. w = self
  1004. while w.master: w = w.master
  1005. return w
  1006. _subst_format = ('%#', '%b', '%f', '%h', '%k',
  1007. '%s', '%t', '%w', '%x', '%y',
  1008. '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
  1009. _subst_format_str = " ".join(_subst_format)
  1010. def _substitute(self, *args):
  1011. """Internal function."""
  1012. if len(args) != len(self._subst_format): return args
  1013. getboolean = self.tk.getboolean
  1014. getint = int
  1015. def getint_event(s):
  1016. """Tk changed behavior in 8.4.2, returning "??" rather more often."""
  1017. try:
  1018. return int(s)
  1019. except ValueError:
  1020. return s
  1021. nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
  1022. # Missing: (a, c, d, m, o, v, B, R)
  1023. e = Event()
  1024. # serial field: valid vor all events
  1025. # number of button: ButtonPress and ButtonRelease events only
  1026. # height field: Configure, ConfigureRequest, Create,
  1027. # ResizeRequest, and Expose events only
  1028. # keycode field: KeyPress and KeyRelease events only
  1029. # time field: "valid for events that contain a time field"
  1030. # width field: Configure, ConfigureRequest, Create, ResizeRequest,
  1031. # and Expose events only
  1032. # x field: "valid for events that contain a x field"
  1033. # y field: "valid for events that contain a y field"
  1034. # keysym as decimal: KeyPress and KeyRelease events only
  1035. # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
  1036. # KeyRelease,and Motion events
  1037. e.serial = getint(nsign)
  1038. e.num = getint_event(b)
  1039. try: e.focus = getboolean(f)
  1040. except TclError: pass
  1041. e.height = getint_event(h)
  1042. e.keycode = getint_event(k)
  1043. e.state = getint_event(s)
  1044. e.time = getint_event(t)
  1045. e.width = getint_event(w)
  1046. e.x = getint_event(x)
  1047. e.y = getint_event(y)
  1048. e.char = A
  1049. try: e.send_event = getboolean(E)
  1050. except TclError: pass
  1051. e.keysym = K
  1052. e.keysym_num = getint_event(N)
  1053. e.type = T
  1054. try:
  1055. e.widget = self._nametowidget(W)
  1056. except KeyError:
  1057. e.widget = W
  1058. e.x_root = getint_event(X)
  1059. e.y_root = getint_event(Y)
  1060. try:
  1061. e.delta = getint(D)
  1062. except ValueError:
  1063. e.delta = 0
  1064. return (e,)
  1065. def _report_exception(self):
  1066. """Internal function."""
  1067. import sys
  1068. exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback
  1069. root = self._root()
  1070. root.report_callback_exception(exc, val, tb)
  1071. def _configure(self, cmd, cnf, kw):
  1072. """Internal function."""
  1073. if kw:
  1074. cnf = _cnfmerge((cnf, kw))
  1075. elif cnf:
  1076. cnf = _cnfmerge(cnf)
  1077. if cnf is None:
  1078. cnf = {}
  1079. for x in self.tk.split(
  1080. self.tk.call(_flatten((self._w, cmd)))):
  1081. cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1082. return cnf
  1083. if type(cnf) is StringType:
  1084. x = self.tk.split(
  1085. self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
  1086. return (x[0][1:],) + x[1:]
  1087. self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
  1088. # These used to be defined in Widget:
  1089. def configure(self, cnf=None, **kw):
  1090. """Configure resources of a widget.
  1091. The values for resources are specified as keyword
  1092. arguments. To get an overview about
  1093. the allowed keyword arguments call the method keys.
  1094. """
  1095. return self._configure('configure', cnf, kw)
  1096. config = configure
  1097. def cget(self, key):
  1098. """Return the resource value for a KEY given as string."""
  1099. return self.tk.call(self._w, 'cget', '-' + key)
  1100. __getitem__ = cget
  1101. def __setitem__(self, key, value):
  1102. self.configure({key: value})
  1103. def __contains__(self, key):
  1104. raise TypeError("Tkinter objects don't support 'in' tests.")
  1105. def keys(self):
  1106. """Return a list of all resource names of this widget."""
  1107. return map(lambda x: x[0][1:],
  1108. self.tk.split(self.tk.call(self._w, 'configure')))
  1109. def __str__(self):
  1110. """Return the window path name of this widget."""
  1111. return self._w
  1112. # Pack methods that apply to the master
  1113. _noarg_ = ['_noarg_']
  1114. def pack_propagate(self, flag=_noarg_):
  1115. """Set or get the status for propagation of geometry information.
  1116. A boolean argument specifies whether the geometry information
  1117. of the slaves will determine the size of this widget. If no argument
  1118. is given the current setting will be returned.
  1119. """
  1120. if flag is Misc._noarg_:
  1121. return self._getboolean(self.tk.call(
  1122. 'pack', 'propagate', self._w))
  1123. else:
  1124. self.tk.call('pack', 'propagate', self._w, flag)
  1125. propagate = pack_propagate
  1126. def pack_slaves(self):
  1127. """Return a list of all slaves of this widget
  1128. in its packing order."""
  1129. return map(self._nametowidget,
  1130. self.tk.splitlist(
  1131. self.tk.call('pack', 'slaves', self._w)))
  1132. slaves = pack_slaves
  1133. # Place method that applies to the master
  1134. def place_slaves(self):
  1135. """Return a list of all slaves of this widget
  1136. in its packing order."""
  1137. return map(self._nametowidget,
  1138. self.tk.splitlist(
  1139. self.tk.call(
  1140. 'place', 'slaves', self._w)))
  1141. # Grid methods that apply to the master
  1142. def grid_bbox(self, column=None, row=None, col2=None, row2=None):
  1143. """Return a tuple of integer coordinates for the bounding
  1144. box of