PageRenderTime 81ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/lib-tk/Tkinter.py

http://unladen-swallow.googlecode.com/
Python | 3774 lines | 3749 code | 0 blank | 25 comment | 6 complexity | 77f6245e4d47ba42fe974c0a4dbee464 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  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 this widget controlled by the geometry manager grid.
  1145. If COLUMN, ROW is given the bounding box applies from
  1146. the cell with row and column 0 to the specified
  1147. cell. If COL2 and ROW2 are given the bounding box
  1148. starts at that cell.
  1149. The returned integers specify the offset of the upper left
  1150. corner in the master widget and the width and height.
  1151. """
  1152. args = ('grid', 'bbox', self._w)
  1153. if column is not None and row is not None:
  1154. args = args + (column, row)
  1155. if col2 is not None and row2 is not None:
  1156. args = args + (col2, row2)
  1157. return self._getints(self.tk.call(*args)) or None
  1158. bbox = grid_bbox
  1159. def _grid_configure(self, command, index, cnf, kw):
  1160. """Internal function."""
  1161. if type(cnf) is StringType and not kw:
  1162. if cnf[-1:] == '_':
  1163. cnf = cnf[:-1]
  1164. if cnf[:1] != '-':
  1165. cnf = '-'+cnf
  1166. options = (cnf,)
  1167. else:
  1168. options = self._options(cnf, kw)
  1169. if not options:
  1170. res = self.tk.call('grid',
  1171. command, self._w, index)
  1172. words = self.tk.splitlist(res)
  1173. dict = {}
  1174. for i in range(0, len(words), 2):
  1175. key = words[i][1:]
  1176. value = words[i+1]
  1177. if not value:
  1178. value = None
  1179. elif '.' in value:
  1180. value = getdouble(value)
  1181. else:
  1182. value = getint(value)
  1183. dict[key] = value
  1184. return dict
  1185. res = self.tk.call(
  1186. ('grid', command, self._w, index)
  1187. + options)
  1188. if len(options) == 1:
  1189. if not res: return None
  1190. # In Tk 7.5, -width can be a float
  1191. if '.' in res: return getdouble(res)
  1192. return getint(res)
  1193. def grid_columnconfigure(self, index, cnf={}, **kw):
  1194. """Configure column INDEX of a grid.
  1195. Valid resources are minsize (minimum size of the column),
  1196. weight (how much does additional space propagate to this column)
  1197. and pad (how much space to let additionally)."""
  1198. return self._grid_configure('columnconfigure', index, cnf, kw)
  1199. columnconfigure = grid_columnconfigure
  1200. def grid_location(self, x, y):
  1201. """Return a tuple of column and row which identify the cell
  1202. at which the pixel at position X and Y inside the master
  1203. widget is located."""
  1204. return self._getints(
  1205. self.tk.call(
  1206. 'grid', 'location', self._w, x, y)) or None
  1207. def grid_propagate(self, flag=_noarg_):
  1208. """Set or get the status for propagation of geometry information.
  1209. A boolean argument specifies whether the geometry information
  1210. of the slaves will determine the size of this widget. If no argument
  1211. is given, the current setting will be returned.
  1212. """
  1213. if flag is Misc._noarg_:
  1214. return self._getboolean(self.tk.call(
  1215. 'grid', 'propagate', self._w))
  1216. else:
  1217. self.tk.call('grid', 'propagate', self._w, flag)
  1218. def grid_rowconfigure(self, index, cnf={}, **kw):
  1219. """Configure row INDEX of a grid.
  1220. Valid resources are minsize (minimum size of the row),
  1221. weight (how much does additional space propagate to this row)
  1222. and pad (how much space to let additionally)."""
  1223. return self._grid_configure('rowconfigure', index, cnf, kw)
  1224. rowconfigure = grid_rowconfigure
  1225. def grid_size(self):
  1226. """Return a tuple of the number of column and rows in the grid."""
  1227. return self._getints(
  1228. self.tk.call('grid', 'size', self._w)) or None
  1229. size = grid_size
  1230. def grid_slaves(self, row=None, column=None):
  1231. """Return a list of all slaves of this widget
  1232. in its packing order."""
  1233. args = ()
  1234. if row is not None:
  1235. args = args + ('-row', row)
  1236. if column is not None:
  1237. args = args + ('-column', column)
  1238. return map(self._nametowidget,
  1239. self.tk.splitlist(self.tk.call(
  1240. ('grid', 'slaves', self._w) + args)))
  1241. # Support for the "event" command, new in Tk 4.2.
  1242. # By Case Roole.
  1243. def event_add(self, virtual, *sequences):
  1244. """Bind a virtual event VIRTUAL (of the form <<Name>>)
  1245. to an event SEQUENCE such that the virtual event is triggered
  1246. whenever SEQUENCE occurs."""
  1247. args = ('event', 'add', virtual) + sequences
  1248. self.tk.call(args)
  1249. def event_delete(self, virtual, *sequences):
  1250. """Unbind a virtual event VIRTUAL from SEQUENCE."""
  1251. args = ('event', 'delete', virtual) + sequences
  1252. self.tk.call(args)
  1253. def event_generate(self, sequence, **kw):
  1254. """Generate an event SEQUENCE. Additional
  1255. keyword arguments specify parameter of the event
  1256. (e.g. x, y, rootx, rooty)."""
  1257. args = ('event', 'generate', self._w, sequence)
  1258. for k, v in kw.items():
  1259. args = args + ('-%s' % k, str(v))
  1260. self.tk.call(args)
  1261. def event_info(self, virtual=None):
  1262. """Return a list of all virtual events or the information
  1263. about the SEQUENCE bound to the virtual event VIRTUAL."""
  1264. return self.tk.splitlist(
  1265. self.tk.call('event', 'info', virtual))
  1266. # Image related commands
  1267. def image_names(self):
  1268. """Return a list of all existing image names."""
  1269. return self.tk.call('image', 'names')
  1270. def image_types(self):
  1271. """Return a list of all available image types (e.g. phote bitmap)."""
  1272. return self.tk.call('image', 'types')
  1273. class CallWrapper:
  1274. """Internal class. Stores function to call when some user
  1275. defined Tcl function is called e.g. after an event occurred."""
  1276. def __init__(self, func, subst, widget):
  1277. """Store FUNC, SUBST and WIDGET as members."""
  1278. self.func = func
  1279. self.subst = subst
  1280. self.widget = widget
  1281. def __call__(self, *args):
  1282. """Apply first function SUBST to arguments, than FUNC."""
  1283. try:
  1284. if self.subst:
  1285. args = self.subst(*args)
  1286. return self.func(*args)
  1287. except SystemExit, msg:
  1288. raise SystemExit, msg
  1289. except:
  1290. self.widget._report_exception()
  1291. class Wm:
  1292. """Provides functions for the communication with the window manager."""
  1293. def wm_aspect(self,
  1294. minNumer=None, minDenom=None,
  1295. maxNumer=None, maxDenom=None):
  1296. """Instruct the window manager to set the aspect ratio (width/height)
  1297. of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
  1298. of the actual values if no argument is given."""
  1299. return self._getints(
  1300. self.tk.call('wm', 'aspect', self._w,
  1301. minNumer, minDenom,
  1302. maxNumer, maxDenom))
  1303. aspect = wm_aspect
  1304. def wm_attributes(self, *args):
  1305. """This subcommand returns or sets platform specific attributes
  1306. The first form returns a list of the platform specific flags and
  1307. their values. The second form returns the value for the specific
  1308. option. The third form sets one or more of the values. The values
  1309. are as follows:
  1310. On Windows, -disabled gets or sets whether the window is in a
  1311. disabled state. -toolwindow gets or sets the style of the window
  1312. to toolwindow (as defined in the MSDN). -topmost gets or sets
  1313. whether this is a topmost window (displays above all other
  1314. windows).
  1315. On Macintosh, XXXXX
  1316. On Unix, there are currently no special attribute values.
  1317. """
  1318. args = ('wm', 'attributes', self._w) + args
  1319. return self.tk.call(args)
  1320. attributes=wm_attributes
  1321. def wm_client(self, name=None):
  1322. """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
  1323. current value."""
  1324. return self.tk.call('wm', 'client', self._w, name)
  1325. client = wm_client
  1326. def wm_colormapwindows(self, *wlist):
  1327. """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
  1328. of this widget. This list contains windows whose colormaps differ from their
  1329. parents. Return current list of widgets if WLIST is empty."""
  1330. if len(wlist) > 1:
  1331. wlist = (wlist,) # Tk needs a list of windows here
  1332. args = ('wm', 'colormapwindows', self._w) + wlist
  1333. return map(self._nametowidget, self.tk.call(args))
  1334. colormapwindows = wm_colormapwindows
  1335. def wm_command(self, value=None):
  1336. """Store VALUE in WM_COMMAND property. It is the command
  1337. which shall be used to invoke the application. Return current
  1338. command if VALUE is None."""
  1339. return self.tk.call('wm', 'command', self._w, value)
  1340. command = wm_command
  1341. def wm_deiconify(self):
  1342. """Deiconify this widget. If it was never mapped it will not be mapped.
  1343. On Windows it will raise this widget and give it the focus."""
  1344. return self.tk.call('wm', 'deiconify', self._w)
  1345. deiconify = wm_deiconify
  1346. def wm_focusmodel(self, model=None):
  1347. """Set focus model to MODEL. "active" means that this widget will claim
  1348. the focus itself, "passive" means that the window manager shall give
  1349. the focus. Return current focus model if MODEL is None."""
  1350. return self.tk.call('wm', 'focusmodel', self._w, model)
  1351. focusmodel = wm_focusmodel
  1352. def wm_frame(self):
  1353. """Return identifier for decorative frame of this widget if present."""
  1354. return self.tk.call('wm', 'frame', self._w)
  1355. frame = wm_frame
  1356. def wm_geometry(self, newGeometry=None):
  1357. """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
  1358. current value if None is given."""
  1359. return self.tk.call('wm', 'geometry', self._w, newGeometry)
  1360. geometry = wm_geometry
  1361. def wm_grid(self,
  1362. baseWidth=None, baseHeight=None,
  1363. widthInc=None, heightInc=None):
  1364. """Instruct the window manager that this widget shall only be
  1365. resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
  1366. height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
  1367. number of grid units requested in Tk_GeometryRequest."""
  1368. return self._getints(self.tk.call(
  1369. 'wm', 'grid', self._w,
  1370. baseWidth, baseHeight, widthInc, heightInc))
  1371. grid = wm_grid
  1372. def wm_group(self, pathName=None):
  1373. """Set the group leader widgets for related widgets to PATHNAME. Return
  1374. the group leader of this widget if None is given."""
  1375. return self.tk.call('wm', 'group', self._w, pathName)
  1376. group = wm_group
  1377. def wm_iconbitmap(self, bitmap=None, default=None):
  1378. """Set bitmap for the iconified widget to BITMAP. Return
  1379. the bitmap if None is given.
  1380. Under Windows, the DEFAULT parameter can be used to set the icon
  1381. for the widget and any descendents that don't have an icon set
  1382. explicitly. DEFAULT can be the relative path to a .ico file
  1383. (example: root.iconbitmap(default='myicon.ico') ). See Tk
  1384. documentation for more information."""
  1385. if default:
  1386. return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
  1387. else:
  1388. return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  1389. iconbitmap = wm_iconbitmap
  1390. def wm_iconify(self):
  1391. """Display widget as icon."""
  1392. return self.tk.call('wm', 'iconify', self._w)
  1393. iconify = wm_iconify
  1394. def wm_iconmask(self, bitmap=None):
  1395. """Set mask for the icon bitmap of this widget. Return the
  1396. mask if None is given."""
  1397. return self.tk.call('wm', 'iconmask', self._w, bitmap)
  1398. iconmask = wm_iconmask
  1399. def wm_iconname(self, newName=None):
  1400. """Set the name of the icon for this widget. Return the name if
  1401. None is given."""
  1402. return self.tk.call('wm', 'iconname', self._w, newName)
  1403. iconname = wm_iconname
  1404. def wm_iconposition(self, x=None, y=None):
  1405. """Set the position of the icon of this widget to X and Y. Return
  1406. a tuple of the current values of X and X if None is given."""
  1407. return self._getints(self.tk.call(
  1408. 'wm', 'iconposition', self._w, x, y))
  1409. iconposition = wm_iconposition
  1410. def wm_iconwindow(self, pathName=None):
  1411. """Set widget PATHNAME to be displayed instead of icon. Return the current
  1412. value if None is given."""
  1413. return self.tk.call('wm', 'iconwindow', self._w, pathName)
  1414. iconwindow = wm_iconwindow
  1415. def wm_maxsize(self, width=None, height=None):
  1416. """Set max WIDTH and HEIGHT for this widget. If the window is gridded
  1417. the values are given in grid units. Return the current values if None
  1418. is given."""
  1419. return self._getints(self.tk.call(
  1420. 'wm', 'maxsize', self._w, width, height))
  1421. maxsize = wm_maxsize
  1422. def wm_minsize(self, width=None, height=None):
  1423. """Set min WIDTH and HEIGHT for this widget. If the window is gridded
  1424. the values are given in grid units. Return the current values if None
  1425. is given."""
  1426. return self._getints(self.tk.call(
  1427. 'wm', 'minsize', self._w, width, height))
  1428. minsize = wm_minsize
  1429. def wm_overrideredirect(self, boolean=None):
  1430. """Instruct the window manager to ignore this widget
  1431. if BOOLEAN is given with 1. Return the current value if None
  1432. is given."""
  1433. return self._getboolean(self.tk.call(
  1434. 'wm', 'overrideredirect', self._w, boolean))
  1435. overrideredirect = wm_overrideredirect
  1436. def wm_positionfrom(self, who=None):
  1437. """Instruct the window manager that the position of this widget shall
  1438. be defined by the user if WHO is "user", and by its own policy if WHO is
  1439. "program"."""
  1440. return self.tk.call('wm', 'positionfrom', self._w, who)
  1441. positionfrom = wm_positionfrom
  1442. def wm_protocol(self, name=None, func=None):
  1443. """Bind function FUNC to command NAME for this widget.
  1444. Return the function bound to NAME if None is given. NAME could be
  1445. e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
  1446. if hasattr(func, '__call__'):
  1447. command = self._register(func)
  1448. else:
  1449. command = func
  1450. return self.tk.call(
  1451. 'wm', 'protocol', self._w, name, command)
  1452. protocol = wm_protocol
  1453. def wm_resizable(self, width=None, height=None):
  1454. """Instruct the window manager whether this width can be resized
  1455. in WIDTH or HEIGHT. Both values are boolean values."""
  1456. return self.tk.call('wm', 'resizable', self._w, width, height)
  1457. resizable = wm_resizable
  1458. def wm_sizefrom(self, who=None):
  1459. """Instruct the window manager that the size of this widget shall
  1460. be defined by the user if WHO is "user", and by its own policy if WHO is
  1461. "program"."""
  1462. return self.tk.call('wm', 'sizefrom', self._w, who)
  1463. sizefrom = wm_sizefrom
  1464. def wm_state(self, newstate=None):
  1465. """Query or set the state of this widget as one of normal, icon,
  1466. iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
  1467. return self.tk.call('wm', 'state', self._w, newstate)
  1468. state = wm_state
  1469. def wm_title(self, string=None):
  1470. """Set the title of this widget."""
  1471. return self.tk.call('wm', 'title', self._w, string)
  1472. title = wm_title
  1473. def wm_transient(self, master=None):
  1474. """Instruct the window manager that this widget is transient
  1475. with regard to widget MASTER."""
  1476. return self.tk.call('wm', 'transient', self._w, master)
  1477. transient = wm_transient
  1478. def wm_withdraw(self):
  1479. """Withdraw this widget from the screen such that it is unmapped
  1480. and forgotten by the window manager. Re-draw it with wm_deiconify."""
  1481. return self.tk.call('wm', 'withdraw', self._w)
  1482. withdraw = wm_withdraw
  1483. class Tk(Misc, Wm):
  1484. """Toplevel widget of Tk which represents mostly the main window
  1485. of an appliation. It has an associated Tcl interpreter."""
  1486. _w = '.'
  1487. def __init__(self, screenName=None, baseName=None, className='Tk',
  1488. useTk=1, sync=0, use=None):
  1489. """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
  1490. be created. BASENAME will be used for the identification of the profile file (see
  1491. readprofile).
  1492. It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
  1493. is the name of the widget class."""
  1494. self.master = None
  1495. self.children = {}
  1496. self._tkloaded = 0
  1497. # to avoid recursions in the getattr code in case of failure, we
  1498. # ensure that self.tk is always _something_.
  1499. self.tk = None
  1500. if baseName is None:
  1501. import sys, os
  1502. baseName = os.path.basename(sys.argv[0])
  1503. baseName, ext = os.path.splitext(baseName)
  1504. if ext not in ('.py', '.pyc', '.pyo'):
  1505. baseName = baseName + ext
  1506. interactive = 0
  1507. self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
  1508. if useTk:
  1509. self._loadtk()
  1510. self.readprofile(baseName, className)
  1511. def loadtk(self):
  1512. if not self._tkloaded:
  1513. self.tk.loadtk()
  1514. self._loadtk()
  1515. def _loadtk(self):
  1516. self._tkloaded = 1
  1517. global _default_root
  1518. # Version sanity checks
  1519. tk_version = self.tk.getvar('tk_version')
  1520. if tk_version != _tkinter.TK_VERSION:
  1521. raise RuntimeError, \
  1522. "tk.h version (%s) doesn't match libtk.a version (%s)" \
  1523. % (_tkinter.TK_VERSION, tk_version)
  1524. # Under unknown circumstances, tcl_version gets coerced to float
  1525. tcl_version = str(self.tk.getvar('tcl_version'))
  1526. if tcl_version != _tkinter.TCL_VERSION:
  1527. raise RuntimeError, \
  1528. "tcl.h version (%s) doesn't match libtcl.a version (%s)" \
  1529. % (_tkinter.TCL_VERSION, tcl_version)
  1530. if TkVersion < 4.0:
  1531. raise RuntimeError, \
  1532. "Tk 4.0 or higher is required; found Tk %s" \
  1533. % str(TkVersion)
  1534. # Create and register the tkerror and exit commands
  1535. # We need to inline parts of _register here, _ register
  1536. # would register differently-named commands.
  1537. if self._tclCommands is None:
  1538. self._tclCommands = []
  1539. self.tk.createcommand('tkerror', _tkerror)
  1540. self.tk.createcommand('exit', _exit)
  1541. self._tclCommands.append('tkerror')
  1542. self._tclCommands.append('exit')
  1543. if _support_default_root and not _default_root:
  1544. _default_root = self
  1545. self.protocol("WM_DELETE_WINDOW", self.destroy)
  1546. def destroy(self):
  1547. """Destroy this and all descendants widgets. This will
  1548. end the application of this Tcl interpreter."""
  1549. for c in self.children.values(): c.destroy()
  1550. self.tk.call('destroy', self._w)
  1551. Misc.destroy(self)
  1552. global _default_root
  1553. if _support_default_root and _default_root is self:
  1554. _default_root = None
  1555. def readprofile(self, baseName, className):
  1556. """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
  1557. the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if
  1558. such a file exists in the home directory."""
  1559. import os
  1560. if os.environ.has_key('HOME'): home = os.environ['HOME']
  1561. else: home = os.curdir
  1562. class_tcl = os.path.join(home, '.%s.tcl' % className)
  1563. class_py = os.path.join(home, '.%s.py' % className)
  1564. base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  1565. base_py = os.path.join(home, '.%s.py' % baseName)
  1566. dir = {'self': self}
  1567. exec 'from Tkinter import *' in dir
  1568. if os.path.isfile(class_tcl):
  1569. self.tk.call('source', class_tcl)
  1570. if os.path.isfile(class_py):
  1571. execfile(class_py, dir)
  1572. if os.path.isfile(base_tcl):
  1573. self.tk.call('source', base_tcl)
  1574. if os.path.isfile(base_py):
  1575. execfile(base_py, dir)
  1576. def report_callback_exception(self, exc, val, tb):
  1577. """Internal function. It reports exception on sys.stderr."""
  1578. import traceback, sys
  1579. sys.stderr.write("Exception in Tkinter callback\n")
  1580. sys.last_type = exc
  1581. sys.last_value = val
  1582. sys.last_traceback = tb
  1583. traceback.print_exception(exc, val, tb)
  1584. def __getattr__(self, attr):
  1585. "Delegate attribute access to the interpreter object"
  1586. return getattr(self.tk, attr)
  1587. # Ideally, the classes Pack, Place and Grid disappear, the
  1588. # pack/place/grid methods are defined on the Widget class, and
  1589. # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
  1590. # ...), with pack(), place() and grid() being short for
  1591. # pack_configure(), place_configure() and grid_columnconfigure(), and
  1592. # forget() being short for pack_forget(). As a practical matter, I'm
  1593. # afraid that there is too much code out there that may be using the
  1594. # Pack, Place or Grid class, so I leave them intact -- but only as
  1595. # backwards compatibility features. Also note that those methods that
  1596. # take a master as argument (e.g. pack_propagate) have been moved to
  1597. # the Misc class (which now incorporates all methods common between
  1598. # toplevel and interior widgets). Again, for compatibility, these are
  1599. # copied into the Pack, Place or Grid class.
  1600. def Tcl(screenName=None, baseName=None, className='Tk', useTk=0):
  1601. return Tk(screenName, baseName, className, useTk)
  1602. class Pack:
  1603. """Geometry manager Pack.
  1604. Base class to use the methods pack_* in every widget."""
  1605. def pack_configure(self, cnf={}, **kw):
  1606. """Pack a widget in the parent widget. Use as options:
  1607. after=widget - pack it after you have packed widget
  1608. anchor=NSEW (or subset) - position widget according to
  1609. given direction
  1610. before=widget - pack it before you will pack widget
  1611. expand=bool - expand widget if parent size grows
  1612. fill=NONE or X or Y or BOTH - fill widget if widget grows
  1613. in=master - use master to contain this widget
  1614. in_=master - see 'in' option description
  1615. ipadx=amount - add internal padding in x direction
  1616. ipady=amount - add internal padding in y direction
  1617. padx=amount - add padding in x direction
  1618. pady=amount - add padding in y direction
  1619. side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
  1620. """
  1621. self.tk.call(
  1622. ('pack', 'configure', self._w)
  1623. + self._options(cnf, kw))
  1624. pack = configure = config = pack_configure
  1625. def pack_forget(self):
  1626. """Unmap this widget and do not use it for the packing order."""
  1627. self.tk.call('pack', 'forget', self._w)
  1628. forget = pack_forget
  1629. def pack_info(self):
  1630. """Return information about the packing options
  1631. for this widget."""
  1632. words = self.tk.splitlist(
  1633. self.tk.call('pack', 'info', self._w))
  1634. dict = {}
  1635. for i in range(0, len(words), 2):
  1636. key = words[i][1:]
  1637. value = words[i+1]
  1638. if value[:1] == '.':
  1639. value = self._nametowidget(value)
  1640. dict[key] = value
  1641. return dict
  1642. info = pack_info
  1643. propagate = pack_propagate = Misc.pack_propagate
  1644. slaves = pack_slaves = Misc.pack_slaves
  1645. class Place:
  1646. """Geometry manager Place.
  1647. Base class to use the methods place_* in every widget."""
  1648. def place_configure(self, cnf={}, **kw):
  1649. """Place a widget in the parent widget. Use as options:
  1650. in=master - master relative to which the widget is placed
  1651. in_=master - see 'in' option description
  1652. x=amount - locate anchor of this widget at position x of master
  1653. y=amount - locate anchor of this widget at position y of master
  1654. relx=amount - locate anchor of this widget between 0.0 and 1.0
  1655. relative to width of master (1.0 is right edge)
  1656. rely=amount - locate anchor of this widget between 0.0 and 1.0
  1657. relative to height of master (1.0 is bottom edge)
  1658. anchor=NSEW (or subset) - position anchor according to given direction
  1659. width=amount - width of this widget in pixel
  1660. height=amount - height of this widget in pixel
  1661. relwidth=amount - width of this widget between 0.0 and 1.0
  1662. relative to width of master (1.0 is the same width
  1663. as the master)
  1664. relheight=amount - height of this widget between 0.0 and 1.0
  1665. relative to height of master (1.0 is the same
  1666. height as the master)
  1667. bordermode="inside" or "outside" - whether to take border width of
  1668. master widget into account
  1669. """
  1670. self.tk.call(
  1671. ('place', 'configure', self._w)
  1672. + self._options(cnf, kw))
  1673. place = configure = config = place_configure
  1674. def place_forget(self):
  1675. """Unmap this widget."""
  1676. self.tk.call('place', 'forget', self._w)
  1677. forget = place_forget
  1678. def place_info(self):
  1679. """Return information about the placing options
  1680. for this widget."""
  1681. words = self.tk.splitlist(
  1682. self.tk.call('place', 'info', self._w))
  1683. dict = {}
  1684. for i in range(0, len(words), 2):
  1685. key = words[i][1:]
  1686. value = words[i+1]
  1687. if value[:1] == '.':
  1688. value = self._nametowidget(value)
  1689. dict[key] = value
  1690. return dict
  1691. info = place_info
  1692. slaves = place_slaves = Misc.place_slaves
  1693. class Grid:
  1694. """Geometry manager Grid.
  1695. Base class to use the methods grid_* in every widget."""
  1696. # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
  1697. def grid_configure(self, cnf={}, **kw):
  1698. """Position a widget in the parent widget in a grid. Use as options:
  1699. column=number - use cell identified with given column (starting with 0)
  1700. columnspan=number - this widget will span several columns
  1701. in=master - use master to contain this widget
  1702. in_=master - see 'in' option description
  1703. ipadx=amount - add internal padding in x direction
  1704. ipady=amount - add internal padding in y direction
  1705. padx=amount - add padding in x direction
  1706. pady=amount - add padding in y direction
  1707. row=number - use cell identified with given row (starting with 0)
  1708. rowspan=number - this widget will span several rows
  1709. sticky=NSEW - if cell is larger on which sides will this
  1710. widget stick to the cell boundary
  1711. """
  1712. self.tk.call(
  1713. ('grid', 'configure', self._w)
  1714. + self._options(cnf, kw))
  1715. grid = configure = config = grid_configure
  1716. bbox = grid_bbox = Misc.grid_bbox
  1717. columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  1718. def grid_forget(self):
  1719. """Unmap this widget."""
  1720. self.tk.call('grid', 'forget', self._w)
  1721. forget = grid_forget
  1722. def grid_remove(self):
  1723. """Unmap this widget but remember the grid options."""
  1724. self.tk.call('grid', 'remove', self._w)
  1725. def grid_info(self):
  1726. """Return information about the options
  1727. for positioning this widget in a grid."""
  1728. words = self.tk.splitlist(
  1729. self.tk.call('grid', 'info', self._w))
  1730. dict = {}
  1731. for i in range(0, len(words), 2):
  1732. key = words[i][1:]
  1733. value = words[i+1]
  1734. if value[:1] == '.':
  1735. value = self._nametowidget(value)
  1736. dict[key] = value
  1737. return dict
  1738. info = grid_info
  1739. location = grid_location = Misc.grid_location
  1740. propagate = grid_propagate = Misc.grid_propagate
  1741. rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  1742. size = grid_size = Misc.grid_size
  1743. slaves = grid_slaves = Misc.grid_slaves
  1744. class BaseWidget(Misc):
  1745. """Internal class."""
  1746. def _setup(self, master, cnf):
  1747. """Internal function. Sets up information about children."""
  1748. if _support_default_root:
  1749. global _default_root
  1750. if not master:
  1751. if not _default_root:
  1752. _default_root = Tk()
  1753. master = _default_root
  1754. self.master = master
  1755. self.tk = master.tk
  1756. name = None
  1757. if cnf.has_key('name'):
  1758. name = cnf['name']
  1759. del cnf['name']
  1760. if not name:
  1761. name = repr(id(self))
  1762. self._name = name
  1763. if master._w=='.':
  1764. self._w = '.' + name
  1765. else:
  1766. self._w = master._w + '.' + name
  1767. self.children = {}
  1768. if self.master.children.has_key(self._name):
  1769. self.master.children[self._name].destroy()
  1770. self.master.children[self._name] = self
  1771. def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
  1772. """Construct a widget with the parent widget MASTER, a name WIDGETNAME
  1773. and appropriate options."""
  1774. if kw:
  1775. cnf = _cnfmerge((cnf, kw))
  1776. self.widgetName = widgetName
  1777. BaseWidget._setup(self, master, cnf)
  1778. if self._tclCommands is None:
  1779. self._tclCommands = []
  1780. classes = []
  1781. for k in cnf.keys():
  1782. if type(k) is ClassType:
  1783. classes.append((k, cnf[k]))
  1784. del cnf[k]
  1785. self.tk.call(
  1786. (widgetName, self._w) + extra + self._options(cnf))
  1787. for k, v in classes:
  1788. k.configure(self, v)
  1789. def destroy(self):
  1790. """Destroy this and all descendants widgets."""
  1791. for c in self.children.values(): c.destroy()
  1792. self.tk.call('destroy', self._w)
  1793. if self.master.children.has_key(self._name):
  1794. del self.master.children[self._name]
  1795. Misc.destroy(self)
  1796. def _do(self, name, args=()):
  1797. # XXX Obsolete -- better use self.tk.call directly!
  1798. return self.tk.call((self._w, name) + args)
  1799. class Widget(BaseWidget, Pack, Place, Grid):
  1800. """Internal class.
  1801. Base class for a widget which can be positioned with the geometry managers
  1802. Pack, Place or Grid."""
  1803. pass
  1804. class Toplevel(BaseWidget, Wm):
  1805. """Toplevel widget, e.g. for dialogs."""
  1806. def __init__(self, master=None, cnf={}, **kw):
  1807. """Construct a toplevel widget with the parent MASTER.
  1808. Valid resource names: background, bd, bg, borderwidth, class,
  1809. colormap, container, cursor, height, highlightbackground,
  1810. highlightcolor, highlightthickness, menu, relief, screen, takefocus,
  1811. use, visual, width."""
  1812. if kw:
  1813. cnf = _cnfmerge((cnf, kw))
  1814. extra = ()
  1815. for wmkey in ['screen', 'class_', 'class', 'visual',
  1816. 'colormap']:
  1817. if cnf.has_key(wmkey):
  1818. val = cnf[wmkey]
  1819. # TBD: a hack needed because some keys
  1820. # are not valid as keyword arguments
  1821. if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
  1822. else: opt = '-'+wmkey
  1823. extra = extra + (opt, val)
  1824. del cnf[wmkey]
  1825. BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
  1826. root = self._root()
  1827. self.iconname(root.iconname())
  1828. self.title(root.title())
  1829. self.protocol("WM_DELETE_WINDOW", self.destroy)
  1830. class Button(Widget):
  1831. """Button widget."""
  1832. def __init__(self, master=None, cnf={}, **kw):
  1833. """Construct a button widget with the parent MASTER.
  1834. STANDARD OPTIONS
  1835. activebackground, activeforeground, anchor,
  1836. background, bitmap, borderwidth, cursor,
  1837. disabledforeground, font, foreground
  1838. highlightbackground, highlightcolor,
  1839. highlightthickness, image, justify,
  1840. padx, pady, relief, repeatdelay,
  1841. repeatinterval, takefocus, text,
  1842. textvariable, underline, wraplength
  1843. WIDGET-SPECIFIC OPTIONS
  1844. command, compound, default, height,
  1845. overrelief, state, width
  1846. """
  1847. Widget.__init__(self, master, 'button', cnf, kw)
  1848. def tkButtonEnter(self, *dummy):
  1849. self.tk.call('tkButtonEnter', self._w)
  1850. def tkButtonLeave(self, *dummy):
  1851. self.tk.call('tkButtonLeave', self._w)
  1852. def tkButtonDown(self, *dummy):
  1853. self.tk.call('tkButtonDown', self._w)
  1854. def tkButtonUp(self, *dummy):
  1855. self.tk.call('tkButtonUp', self._w)
  1856. def tkButtonInvoke(self, *dummy):
  1857. self.tk.call('tkButtonInvoke', self._w)
  1858. def flash(self):
  1859. """Flash the button.
  1860. This is accomplished by redisplaying
  1861. the button several times, alternating between active and
  1862. normal colors. At the end of the flash the button is left
  1863. in the same normal/active state as when the command was
  1864. invoked. This command is ignored if the button's state is
  1865. disabled.
  1866. """
  1867. self.tk.call(self._w, 'flash')
  1868. def invoke(self):
  1869. """Invoke the command associated with the button.
  1870. The return value is the return value from the command,
  1871. or an empty string if there is no command associated with
  1872. the button. This command is ignored if the button's state
  1873. is disabled.
  1874. """
  1875. return self.tk.call(self._w, 'invoke')
  1876. # Indices:
  1877. # XXX I don't like these -- take them away
  1878. def AtEnd():
  1879. return 'end'
  1880. def AtInsert(*args):
  1881. s = 'insert'
  1882. for a in args:
  1883. if a: s = s + (' ' + a)
  1884. return s
  1885. def AtSelFirst():
  1886. return 'sel.first'
  1887. def AtSelLast():
  1888. return 'sel.last'
  1889. def At(x, y=None):
  1890. if y is None:
  1891. return '@%r' % (x,)
  1892. else:
  1893. return '@%r,%r' % (x, y)
  1894. class Canvas(Widget):
  1895. """Canvas widget to display graphical elements like lines or text."""
  1896. def __init__(self, master=None, cnf={}, **kw):
  1897. """Construct a canvas widget with the parent MASTER.
  1898. Valid resource names: background, bd, bg, borderwidth, closeenough,
  1899. confine, cursor, height, highlightbackground, highlightcolor,
  1900. highlightthickness, insertbackground, insertborderwidth,
  1901. insertofftime, insertontime, insertwidth, offset, relief,
  1902. scrollregion, selectbackground, selectborderwidth, selectforeground,
  1903. state, takefocus, width, xscrollcommand, xscrollincrement,
  1904. yscrollcommand, yscrollincrement."""
  1905. Widget.__init__(self, master, 'canvas', cnf, kw)
  1906. def addtag(self, *args):
  1907. """Internal function."""
  1908. self.tk.call((self._w, 'addtag') + args)
  1909. def addtag_above(self, newtag, tagOrId):
  1910. """Add tag NEWTAG to all items above TAGORID."""
  1911. self.addtag(newtag, 'above', tagOrId)
  1912. def addtag_all(self, newtag):
  1913. """Add tag NEWTAG to all items."""
  1914. self.addtag(newtag, 'all')
  1915. def addtag_below(self, newtag, tagOrId):
  1916. """Add tag NEWTAG to all items below TAGORID."""
  1917. self.addtag(newtag, 'below', tagOrId)
  1918. def addtag_closest(self, newtag, x, y, halo=None, start=None):
  1919. """Add tag NEWTAG to item which is closest to pixel at X, Y.
  1920. If several match take the top-most.
  1921. All items closer than HALO are considered overlapping (all are
  1922. closests). If START is specified the next below this tag is taken."""
  1923. self.addtag(newtag, 'closest', x, y, halo, start)
  1924. def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  1925. """Add tag NEWTAG to all items in the rectangle defined
  1926. by X1,Y1,X2,Y2."""
  1927. self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  1928. def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  1929. """Add tag NEWTAG to all items which overlap the rectangle
  1930. defined by X1,Y1,X2,Y2."""
  1931. self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  1932. def addtag_withtag(self, newtag, tagOrId):
  1933. """Add tag NEWTAG to all items with TAGORID."""
  1934. self.addtag(newtag, 'withtag', tagOrId)
  1935. def bbox(self, *args):
  1936. """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  1937. which encloses all items with tags specified as arguments."""
  1938. return self._getints(
  1939. self.tk.call((self._w, 'bbox') + args)) or None
  1940. def tag_unbind(self, tagOrId, sequence, funcid=None):
  1941. """Unbind for all items with TAGORID for event SEQUENCE the
  1942. function identified with FUNCID."""
  1943. self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  1944. if funcid:
  1945. self.deletecommand(funcid)
  1946. def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
  1947. """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
  1948. An additional boolean parameter ADD specifies whether FUNC will be
  1949. called additionally to the other bound function or whether it will
  1950. replace the previous function. See bind for the return value."""
  1951. return self._bind((self._w, 'bind', tagOrId),
  1952. sequence, func, add)
  1953. def canvasx(self, screenx, gridspacing=None):
  1954. """Return the canvas x coordinate of pixel position SCREENX rounded
  1955. to nearest multiple of GRIDSPACING units."""
  1956. return getdouble(self.tk.call(
  1957. self._w, 'canvasx', screenx, gridspacing))
  1958. def canvasy(self, screeny, gridspacing=None):
  1959. """Return the canvas y coordinate of pixel position SCREENY rounded
  1960. to nearest multiple of GRIDSPACING units."""
  1961. return getdouble(self.tk.call(
  1962. self._w, 'canvasy', screeny, gridspacing))
  1963. def coords(self, *args):
  1964. """Return a list of coordinates for the item given in ARGS."""
  1965. # XXX Should use _flatten on args
  1966. return map(getdouble,
  1967. self.tk.splitlist(
  1968. self.tk.call((self._w, 'coords') + args)))
  1969. def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
  1970. """Internal function."""
  1971. args = _flatten(args)
  1972. cnf = args[-1]
  1973. if type(cnf) in (DictionaryType, TupleType):
  1974. args = args[:-1]
  1975. else:
  1976. cnf = {}
  1977. return getint(self.tk.call(
  1978. self._w, 'create', itemType,
  1979. *(args + self._options(cnf, kw))))
  1980. def create_arc(self, *args, **kw):
  1981. """Create arc shaped region with coordinates x1,y1,x2,y2."""
  1982. return self._create('arc', args, kw)
  1983. def create_bitmap(self, *args, **kw):
  1984. """Create bitmap with coordinates x1,y1."""
  1985. return self._create('bitmap', args, kw)
  1986. def create_image(self, *args, **kw):
  1987. """Create image item with coordinates x1,y1."""
  1988. return self._create('image', args, kw)
  1989. def create_line(self, *args, **kw):
  1990. """Create line with coordinates x1,y1,...,xn,yn."""
  1991. return self._create('line', args, kw)
  1992. def create_oval(self, *args, **kw):
  1993. """Create oval with coordinates x1,y1,x2,y2."""
  1994. return self._create('oval', args, kw)
  1995. def create_polygon(self, *args, **kw):
  1996. """Create polygon with coordinates x1,y1,...,xn,yn."""
  1997. return self._create('polygon', args, kw)
  1998. def create_rectangle(self, *args, **kw):
  1999. """Create rectangle with coordinates x1,y1,x2,y2."""
  2000. return self._create('rectangle', args, kw)
  2001. def create_text(self, *args, **kw):
  2002. """Create text with coordinates x1,y1."""
  2003. return self._create('text', args, kw)
  2004. def create_window(self, *args, **kw):
  2005. """Create window with coordinates x1,y1,x2,y2."""
  2006. return self._create('window', args, kw)
  2007. def dchars(self, *args):
  2008. """Delete characters of text items identified by tag or id in ARGS (possibly
  2009. several times) from FIRST to LAST character (including)."""
  2010. self.tk.call((self._w, 'dchars') + args)
  2011. def delete(self, *args):
  2012. """Delete items identified by all tag or ids contained in ARGS."""
  2013. self.tk.call((self._w, 'delete') + args)
  2014. def dtag(self, *args):
  2015. """Delete tag or id given as last arguments in ARGS from items
  2016. identified by first argument in ARGS."""
  2017. self.tk.call((self._w, 'dtag') + args)
  2018. def find(self, *args):
  2019. """Internal function."""
  2020. return self._getints(
  2021. self.tk.call((self._w, 'find') + args)) or ()
  2022. def find_above(self, tagOrId):
  2023. """Return items above TAGORID."""
  2024. return self.find('above', tagOrId)
  2025. def find_all(self):
  2026. """Return all items."""
  2027. return self.find('all')
  2028. def find_below(self, tagOrId):
  2029. """Return all items below TAGORID."""
  2030. return self.find('below', tagOrId)
  2031. def find_closest(self, x, y, halo=None, start=None):
  2032. """Return item which is closest to pixel at X, Y.
  2033. If several match take the top-most.
  2034. All items closer than HALO are considered overlapping (all are
  2035. closests). If START is specified the next below this tag is taken."""
  2036. return self.find('closest', x, y, halo, start)
  2037. def find_enclosed(self, x1, y1, x2, y2):
  2038. """Return all items in rectangle defined
  2039. by X1,Y1,X2,Y2."""
  2040. return self.find('enclosed', x1, y1, x2, y2)
  2041. def find_overlapping(self, x1, y1, x2, y2):
  2042. """Return all items which overlap the rectangle
  2043. defined by X1,Y1,X2,Y2."""
  2044. return self.find('overlapping', x1, y1, x2, y2)
  2045. def find_withtag(self, tagOrId):
  2046. """Return all items with TAGORID."""
  2047. return self.find('withtag', tagOrId)
  2048. def focus(self, *args):
  2049. """Set focus to the first item specified in ARGS."""
  2050. return self.tk.call((self._w, 'focus') + args)
  2051. def gettags(self, *args):
  2052. """Return tags associated with the first item specified in ARGS."""
  2053. return self.tk.splitlist(
  2054. self.tk.call((self._w, 'gettags') + args))
  2055. def icursor(self, *args):
  2056. """Set cursor at position POS in the item identified by TAGORID.
  2057. In ARGS TAGORID must be first."""
  2058. self.tk.call((self._w, 'icursor') + args)
  2059. def index(self, *args):
  2060. """Return position of cursor as integer in item specified in ARGS."""
  2061. return getint(self.tk.call((self._w, 'index') + args))
  2062. def insert(self, *args):
  2063. """Insert TEXT in item TAGORID at position POS. ARGS must
  2064. be TAGORID POS TEXT."""
  2065. self.tk.call((self._w, 'insert') + args)
  2066. def itemcget(self, tagOrId, option):
  2067. """Return the resource value for an OPTION for item TAGORID."""
  2068. return self.tk.call(
  2069. (self._w, 'itemcget') + (tagOrId, '-'+option))
  2070. def itemconfigure(self, tagOrId, cnf=None, **kw):
  2071. """Configure resources of an item TAGORID.
  2072. The values for resources are specified as keyword
  2073. arguments. To get an overview about
  2074. the allowed keyword arguments call the method without arguments.
  2075. """
  2076. return self._configure(('itemconfigure', tagOrId), cnf, kw)
  2077. itemconfig = itemconfigure
  2078. # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
  2079. # so the preferred name for them is tag_lower, tag_raise
  2080. # (similar to tag_bind, and similar to the Text widget);
  2081. # unfortunately can't delete the old ones yet (maybe in 1.6)
  2082. def tag_lower(self, *args):
  2083. """Lower an item TAGORID given in ARGS
  2084. (optional below another item)."""
  2085. self.tk.call((self._w, 'lower') + args)
  2086. lower = tag_lower
  2087. def move(self, *args):
  2088. """Move an item TAGORID given in ARGS."""
  2089. self.tk.call((self._w, 'move') + args)
  2090. def postscript(self, cnf={}, **kw):
  2091. """Print the contents of the canvas to a postscript
  2092. file. Valid options: colormap, colormode, file, fontmap,
  2093. height, pageanchor, pageheight, pagewidth, pagex, pagey,
  2094. rotate, witdh, x, y."""
  2095. return self.tk.call((self._w, 'postscript') +
  2096. self._options(cnf, kw))
  2097. def tag_raise(self, *args):
  2098. """Raise an item TAGORID given in ARGS
  2099. (optional above another item)."""
  2100. self.tk.call((self._w, 'raise') + args)
  2101. lift = tkraise = tag_raise
  2102. def scale(self, *args):
  2103. """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
  2104. self.tk.call((self._w, 'scale') + args)
  2105. def scan_mark(self, x, y):
  2106. """Remember the current X, Y coordinates."""
  2107. self.tk.call(self._w, 'scan', 'mark', x, y)
  2108. def scan_dragto(self, x, y, gain=10):
  2109. """Adjust the view of the canvas to GAIN times the
  2110. difference between X and Y and the coordinates given in
  2111. scan_mark."""
  2112. self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
  2113. def select_adjust(self, tagOrId, index):
  2114. """Adjust the end of the selection near the cursor of an item TAGORID to index."""
  2115. self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  2116. def select_clear(self):
  2117. """Clear the selection if it is in this widget."""
  2118. self.tk.call(self._w, 'select', 'clear')
  2119. def select_from(self, tagOrId, index):
  2120. """Set the fixed end of a selection in item TAGORID to INDEX."""
  2121. self.tk.call(self._w, 'select', 'from', tagOrId, index)
  2122. def select_item(self):
  2123. """Return the item which has the selection."""
  2124. return self.tk.call(self._w, 'select', 'item') or None
  2125. def select_to(self, tagOrId, index):
  2126. """Set the variable end of a selection in item TAGORID to INDEX."""
  2127. self.tk.call(self._w, 'select', 'to', tagOrId, index)
  2128. def type(self, tagOrId):
  2129. """Return the type of the item TAGORID."""
  2130. return self.tk.call(self._w, 'type', tagOrId) or None
  2131. def xview(self, *args):
  2132. """Query and change horizontal position of the view."""
  2133. if not args:
  2134. return self._getdoubles(self.tk.call(self._w, 'xview'))
  2135. self.tk.call((self._w, 'xview') + args)
  2136. def xview_moveto(self, fraction):
  2137. """Adjusts the view in the window so that FRACTION of the
  2138. total width of the canvas is off-screen to the left."""
  2139. self.tk.call(self._w, 'xview', 'moveto', fraction)
  2140. def xview_scroll(self, number, what):
  2141. """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2142. self.tk.call(self._w, 'xview', 'scroll', number, what)
  2143. def yview(self, *args):
  2144. """Query and change vertical position of the view."""
  2145. if not args:
  2146. return self._getdoubles(self.tk.call(self._w, 'yview'))
  2147. self.tk.call((self._w, 'yview') + args)
  2148. def yview_moveto(self, fraction):
  2149. """Adjusts the view in the window so that FRACTION of the
  2150. total height of the canvas is off-screen to the top."""
  2151. self.tk.call(self._w, 'yview', 'moveto', fraction)
  2152. def yview_scroll(self, number, what):
  2153. """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2154. self.tk.call(self._w, 'yview', 'scroll', number, what)
  2155. class Checkbutton(Widget):
  2156. """Checkbutton widget which is either in on- or off-state."""
  2157. def __init__(self, master=None, cnf={}, **kw):
  2158. """Construct a checkbutton widget with the parent MASTER.
  2159. Valid resource names: activebackground, activeforeground, anchor,
  2160. background, bd, bg, bitmap, borderwidth, command, cursor,
  2161. disabledforeground, fg, font, foreground, height,
  2162. highlightbackground, highlightcolor, highlightthickness, image,
  2163. indicatoron, justify, offvalue, onvalue, padx, pady, relief,
  2164. selectcolor, selectimage, state, takefocus, text, textvariable,
  2165. underline, variable, width, wraplength."""
  2166. Widget.__init__(self, master, 'checkbutton', cnf, kw)
  2167. def deselect(self):
  2168. """Put the button in off-state."""
  2169. self.tk.call(self._w, 'deselect')
  2170. def flash(self):
  2171. """Flash the button."""
  2172. self.tk.call(self._w, 'flash')
  2173. def invoke(self):
  2174. """Toggle the button and invoke a command if given as resource."""
  2175. return self.tk.call(self._w, 'invoke')
  2176. def select(self):
  2177. """Put the button in on-state."""
  2178. self.tk.call(self._w, 'select')
  2179. def toggle(self):
  2180. """Toggle the button."""
  2181. self.tk.call(self._w, 'toggle')
  2182. class Entry(Widget):
  2183. """Entry widget which allows to display simple text."""
  2184. def __init__(self, master=None, cnf={}, **kw):
  2185. """Construct an entry widget with the parent MASTER.
  2186. Valid resource names: background, bd, bg, borderwidth, cursor,
  2187. exportselection, fg, font, foreground, highlightbackground,
  2188. highlightcolor, highlightthickness, insertbackground,
  2189. insertborderwidth, insertofftime, insertontime, insertwidth,
  2190. invalidcommand, invcmd, justify, relief, selectbackground,
  2191. selectborderwidth, selectforeground, show, state, takefocus,
  2192. textvariable, validate, validatecommand, vcmd, width,
  2193. xscrollcommand."""
  2194. Widget.__init__(self, master, 'entry', cnf, kw)
  2195. def delete(self, first, last=None):
  2196. """Delete text from FIRST to LAST (not included)."""
  2197. self.tk.call(self._w, 'delete', first, last)
  2198. def get(self):
  2199. """Return the text."""
  2200. return self.tk.call(self._w, 'get')
  2201. def icursor(self, index):
  2202. """Insert cursor at INDEX."""
  2203. self.tk.call(self._w, 'icursor', index)
  2204. def index(self, index):
  2205. """Return position of cursor."""
  2206. return getint(self.tk.call(
  2207. self._w, 'index', index))
  2208. def insert(self, index, string):
  2209. """Insert STRING at INDEX."""
  2210. self.tk.call(self._w, 'insert', index, string)
  2211. def scan_mark(self, x):
  2212. """Remember the current X, Y coordinates."""
  2213. self.tk.call(self._w, 'scan', 'mark', x)
  2214. def scan_dragto(self, x):
  2215. """Adjust the view of the canvas to 10 times the
  2216. difference between X and Y and the coordinates given in
  2217. scan_mark."""
  2218. self.tk.call(self._w, 'scan', 'dragto', x)
  2219. def selection_adjust(self, index):
  2220. """Adjust the end of the selection near the cursor to INDEX."""
  2221. self.tk.call(self._w, 'selection', 'adjust', index)
  2222. select_adjust = selection_adjust
  2223. def selection_clear(self):
  2224. """Clear the selection if it is in this widget."""
  2225. self.tk.call(self._w, 'selection', 'clear')
  2226. select_clear = selection_clear
  2227. def selection_from(self, index):
  2228. """Set the fixed end of a selection to INDEX."""
  2229. self.tk.call(self._w, 'selection', 'from', index)
  2230. select_from = selection_from
  2231. def selection_present(self):
  2232. """Return whether the widget has the selection."""
  2233. return self.tk.getboolean(
  2234. self.tk.call(self._w, 'selection', 'present'))
  2235. select_present = selection_present
  2236. def selection_range(self, start, end):
  2237. """Set the selection from START to END (not included)."""
  2238. self.tk.call(self._w, 'selection', 'range', start, end)
  2239. select_range = selection_range
  2240. def selection_to(self, index):
  2241. """Set the variable end of a selection to INDEX."""
  2242. self.tk.call(self._w, 'selection', 'to', index)
  2243. select_to = selection_to
  2244. def xview(self, index):
  2245. """Query and change horizontal position of the view."""
  2246. self.tk.call(self._w, 'xview', index)
  2247. def xview_moveto(self, fraction):
  2248. """Adjust the view in the window so that FRACTION of the
  2249. total width of the entry is off-screen to the left."""
  2250. self.tk.call(self._w, 'xview', 'moveto', fraction)
  2251. def xview_scroll(self, number, what):
  2252. """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2253. self.tk.call(self._w, 'xview', 'scroll', number, what)
  2254. class Frame(Widget):
  2255. """Frame widget which may contain other widgets and can have a 3D border."""
  2256. def __init__(self, master=None, cnf={}, **kw):
  2257. """Construct a frame widget with the parent MASTER.
  2258. Valid resource names: background, bd, bg, borderwidth, class,
  2259. colormap, container, cursor, height, highlightbackground,
  2260. highlightcolor, highlightthickness, relief, takefocus, visual, width."""
  2261. cnf = _cnfmerge((cnf, kw))
  2262. extra = ()
  2263. if cnf.has_key('class_'):
  2264. extra = ('-class', cnf['class_'])
  2265. del cnf['class_']
  2266. elif cnf.has_key('class'):
  2267. extra = ('-class', cnf['class'])
  2268. del cnf['class']
  2269. Widget.__init__(self, master, 'frame', cnf, {}, extra)
  2270. class Label(Widget):
  2271. """Label widget which can display text and bitmaps."""
  2272. def __init__(self, master=None, cnf={}, **kw):
  2273. """Construct a label widget with the parent MASTER.
  2274. STANDARD OPTIONS
  2275. activebackground, activeforeground, anchor,
  2276. background, bitmap, borderwidth, cursor,
  2277. disabledforeground, font, foreground,
  2278. highlightbackground, highlightcolor,
  2279. highlightthickness, image, justify,
  2280. padx, pady, relief, takefocus, text,
  2281. textvariable, underline, wraplength
  2282. WIDGET-SPECIFIC OPTIONS
  2283. height, state, width
  2284. """
  2285. Widget.__init__(self, master, 'label', cnf, kw)
  2286. class Listbox(Widget):
  2287. """Listbox widget which can display a list of strings."""
  2288. def __init__(self, master=None, cnf={}, **kw):
  2289. """Construct a listbox widget with the parent MASTER.
  2290. Valid resource names: background, bd, bg, borderwidth, cursor,
  2291. exportselection, fg, font, foreground, height, highlightbackground,
  2292. highlightcolor, highlightthickness, relief, selectbackground,
  2293. selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
  2294. width, xscrollcommand, yscrollcommand, listvariable."""
  2295. Widget.__init__(self, master, 'listbox', cnf, kw)
  2296. def activate(self, index):
  2297. """Activate item identified by INDEX."""
  2298. self.tk.call(self._w, 'activate', index)
  2299. def bbox(self, *args):
  2300. """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2301. which encloses the item identified by index in ARGS."""
  2302. return self._getints(
  2303. self.tk.call((self._w, 'bbox') + args)) or None
  2304. def curselection(self):
  2305. """Return list of indices of currently selected item."""
  2306. # XXX Ought to apply self._getints()...
  2307. return self.tk.splitlist(self.tk.call(
  2308. self._w, 'curselection'))
  2309. def delete(self, first, last=None):
  2310. """Delete items from FIRST to LAST (not included)."""
  2311. self.tk.call(self._w, 'delete', first, last)
  2312. def get(self, first, last=None):
  2313. """Get list of items from FIRST to LAST (not included)."""
  2314. if last:
  2315. return self.tk.splitlist(self.tk.call(
  2316. self._w, 'get', first, last))
  2317. else:
  2318. return self.tk.call(self._w, 'get', first)
  2319. def index(self, index):
  2320. """Return index of item identified with INDEX."""
  2321. i = self.tk.call(self._w, 'index', index)
  2322. if i == 'none': return None
  2323. return getint(i)
  2324. def insert(self, index, *elements):
  2325. """Insert ELEMENTS at INDEX."""
  2326. self.tk.call((self._w, 'insert', index) + elements)
  2327. def nearest(self, y):
  2328. """Get index of item which is nearest to y coordinate Y."""
  2329. return getint(self.tk.call(
  2330. self._w, 'nearest', y))
  2331. def scan_mark(self, x, y):
  2332. """Remember the current X, Y coordinates."""
  2333. self.tk.call(self._w, 'scan', 'mark', x, y)
  2334. def scan_dragto(self, x, y):
  2335. """Adjust the view of the listbox to 10 times the
  2336. difference between X and Y and the coordinates given in
  2337. scan_mark."""
  2338. self.tk.call(self._w, 'scan', 'dragto', x, y)
  2339. def see(self, index):
  2340. """Scroll such that INDEX is visible."""
  2341. self.tk.call(self._w, 'see', index)
  2342. def selection_anchor(self, index):
  2343. """Set the fixed end oft the selection to INDEX."""
  2344. self.tk.call(self._w, 'selection', 'anchor', index)
  2345. select_anchor = selection_anchor
  2346. def selection_clear(self, first, last=None):
  2347. """Clear the selection from FIRST to LAST (not included)."""
  2348. self.tk.call(self._w,
  2349. 'selection', 'clear', first, last)
  2350. select_clear = selection_clear
  2351. def selection_includes(self, index):
  2352. """Return 1 if INDEX is part of the selection."""
  2353. return self.tk.getboolean(self.tk.call(
  2354. self._w, 'selection', 'includes', index))
  2355. select_includes = selection_includes
  2356. def selection_set(self, first, last=None):
  2357. """Set the selection from FIRST to LAST (not included) without
  2358. changing the currently selected elements."""
  2359. self.tk.call(self._w, 'selection', 'set', first, last)
  2360. select_set = selection_set
  2361. def size(self):
  2362. """Return the number of elements in the listbox."""
  2363. return getint(self.tk.call(self._w, 'size'))
  2364. def xview(self, *what):
  2365. """Query and change horizontal position of the view."""
  2366. if not what:
  2367. return self._getdoubles(self.tk.call(self._w, 'xview'))
  2368. self.tk.call((self._w, 'xview') + what)
  2369. def xview_moveto(self, fraction):
  2370. """Adjust the view in the window so that FRACTION of the
  2371. total width of the entry is off-screen to the left."""
  2372. self.tk.call(self._w, 'xview', 'moveto', fraction)
  2373. def xview_scroll(self, number, what):
  2374. """Shift the x-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2375. self.tk.call(self._w, 'xview', 'scroll', number, what)
  2376. def yview(self, *what):
  2377. """Query and change vertical position of the view."""
  2378. if not what:
  2379. return self._getdoubles(self.tk.call(self._w, 'yview'))
  2380. self.tk.call((self._w, 'yview') + what)
  2381. def yview_moveto(self, fraction):
  2382. """Adjust the view in the window so that FRACTION of the
  2383. total width of the entry is off-screen to the top."""
  2384. self.tk.call(self._w, 'yview', 'moveto', fraction)
  2385. def yview_scroll(self, number, what):
  2386. """Shift the y-view according to NUMBER which is measured in "units" or "pages" (WHAT)."""
  2387. self.tk.call(self._w, 'yview', 'scroll', number, what)
  2388. def itemcget(self, index, option):
  2389. """Return the resource value for an ITEM and an OPTION."""
  2390. return self.tk.call(
  2391. (self._w, 'itemcget') + (index, '-'+option))
  2392. def itemconfigure(self, index, cnf=None, **kw):
  2393. """Configure resources of an ITEM.
  2394. The values for resources are specified as keyword arguments.
  2395. To get an overview about the allowed keyword arguments
  2396. call the method without arguments.
  2397. Valid resource names: background, bg, foreground, fg,
  2398. selectbackground, selectforeground."""
  2399. return self._configure(('itemconfigure', index), cnf, kw)
  2400. itemconfig = itemconfigure
  2401. class Menu(Widget):
  2402. """Menu widget which allows to display menu bars, pull-down menus and pop-up menus."""
  2403. def __init__(self, master=None, cnf={}, **kw):
  2404. """Construct menu widget with the parent MASTER.
  2405. Valid resource names: activebackground, activeborderwidth,
  2406. activeforeground, background, bd, bg, borderwidth, cursor,
  2407. disabledforeground, fg, font, foreground, postcommand, relief,
  2408. selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
  2409. Widget.__init__(self, master, 'menu', cnf, kw)
  2410. def tk_bindForTraversal(self):
  2411. pass # obsolete since Tk 4.0
  2412. def tk_mbPost(self):
  2413. self.tk.call('tk_mbPost', self._w)
  2414. def tk_mbUnpost(self):
  2415. self.tk.call('tk_mbUnpost')
  2416. def tk_traverseToMenu(self, char):
  2417. self.tk.call('tk_traverseToMenu', self._w, char)
  2418. def tk_traverseWithinMenu(self, char):
  2419. self.tk.call('tk_traverseWithinMenu', self._w, char)
  2420. def tk_getMenuButtons(self):
  2421. return self.tk.call('tk_getMenuButtons', self._w)
  2422. def tk_nextMenu(self, count):
  2423. self.tk.call('tk_nextMenu', count)
  2424. def tk_nextMenuEntry(self, count):
  2425. self.tk.call('tk_nextMenuEntry', count)
  2426. def tk_invokeMenu(self):
  2427. self.tk.call('tk_invokeMenu', self._w)
  2428. def tk_firstMenu(self):
  2429. self.tk.call('tk_firstMenu', self._w)
  2430. def tk_mbButtonDown(self):
  2431. self.tk.call('tk_mbButtonDown', self._w)
  2432. def tk_popup(self, x, y, entry=""):
  2433. """Post the menu at position X,Y with entry ENTRY."""
  2434. self.tk.call('tk_popup', self._w, x, y, entry)
  2435. def activate(self, index):
  2436. """Activate entry at INDEX."""
  2437. self.tk.call(self._w, 'activate', index)
  2438. def add(self, itemType, cnf={}, **kw):
  2439. """Internal function."""
  2440. self.tk.call((self._w, 'add', itemType) +
  2441. self._options(cnf, kw))
  2442. def add_cascade(self, cnf={}, **kw):
  2443. """Add hierarchical menu item."""
  2444. self.add('cascade', cnf or kw)
  2445. def add_checkbutton(self, cnf={}, **kw):
  2446. """Add checkbutton menu item."""
  2447. self.add('checkbutton', cnf or kw)
  2448. def add_command(self, cnf={}, **kw):
  2449. """Add command menu item."""
  2450. self.add('command', cnf or kw)
  2451. def add_radiobutton(self, cnf={}, **kw):
  2452. """Addd radio menu item."""
  2453. self.add('radiobutton', cnf or kw)
  2454. def add_separator(self, cnf={}, **kw):
  2455. """Add separator."""
  2456. self.add('separator', cnf or kw)
  2457. def insert(self, index, itemType, cnf={}, **kw):
  2458. """Internal function."""
  2459. self.tk.call((self._w, 'insert', index, itemType) +
  2460. self._options(cnf, kw))
  2461. def insert_cascade(self, index, cnf={}, **kw):
  2462. """Add hierarchical menu item at INDEX."""
  2463. self.insert(index, 'cascade', cnf or kw)
  2464. def insert_checkbutton(self, index, cnf={}, **kw):
  2465. """Add checkbutton menu item at INDEX."""
  2466. self.insert(index, 'checkbutton', cnf or kw)
  2467. def insert_command(self, index, cnf={}, **kw):
  2468. """Add command menu item at INDEX."""
  2469. self.insert(index, 'command', cnf or kw)
  2470. def insert_radiobutton(self, index, cnf={}, **kw):
  2471. """Addd radio menu item at INDEX."""
  2472. self.insert(index, 'radiobutton', cnf or kw)
  2473. def insert_separator(self, index, cnf={}, **kw):
  2474. """Add separator at INDEX."""
  2475. self.insert(index, 'separator', cnf or kw)
  2476. def delete(self, index1, index2=None):
  2477. """Delete menu items between INDEX1 and INDEX2 (included)."""
  2478. if index2 is None:
  2479. index2 = index1
  2480. num_index1, num_index2 = self.index(index1), self.index(index2)
  2481. if (num_index1 is None) or (num_index2 is None):
  2482. num_index1, num_index2 = 0, -1
  2483. for i in range(num_index1, num_index2 + 1):
  2484. if 'command' in self.entryconfig(i):
  2485. c = str(self.entrycget(i, 'command'))
  2486. if c:
  2487. self.deletecommand(c)
  2488. self.tk.call(self._w, 'delete', index1, index2)
  2489. def entrycget(self, index, option):
  2490. """Return the resource value of an menu item for OPTION at INDEX."""
  2491. return self.tk.call(self._w, 'entrycget', index, '-' + option)
  2492. def entryconfigure(self, index, cnf=None, **kw):
  2493. """Configure a menu item at INDEX."""
  2494. return self._configure(('entryconfigure', index), cnf, kw)
  2495. entryconfig = entryconfigure
  2496. def index(self, index):
  2497. """Return the index of a menu item identified by INDEX."""
  2498. i = self.tk.call(self._w, 'index', index)
  2499. if i == 'none': return None
  2500. return getint(i)
  2501. def invoke(self, index):
  2502. """Invoke a menu item identified by INDEX and execute
  2503. the associated command."""
  2504. return self.tk.call(self._w, 'invoke', index)
  2505. def post(self, x, y):
  2506. """Display a menu at position X,Y."""
  2507. self.tk.call(self._w, 'post', x, y)
  2508. def type(self, index):
  2509. """Return the type of the menu item at INDEX."""
  2510. return self.tk.call(self._w, 'type', index)
  2511. def unpost(self):
  2512. """Unmap a menu."""
  2513. self.tk.call(self._w, 'unpost')
  2514. def yposition(self, index):
  2515. """Return the y-position of the topmost pixel of the menu item at INDEX."""
  2516. return getint(self.tk.call(
  2517. self._w, 'yposition', index))
  2518. class Menubutton(Widget):
  2519. """Menubutton widget, obsolete since Tk8.0."""
  2520. def __init__(self, master=None, cnf={}, **kw):
  2521. Widget.__init__(self, master, 'menubutton', cnf, kw)
  2522. class Message(Widget):
  2523. """Message widget to display multiline text. Obsolete since Label does it too."""
  2524. def __init__(self, master=None, cnf={}, **kw):
  2525. Widget.__init__(self, master, 'message', cnf, kw)
  2526. class Radiobutton(Widget):
  2527. """Radiobutton widget which shows only one of several buttons in on-state."""
  2528. def __init__(self, master=None, cnf={}, **kw):
  2529. """Construct a radiobutton widget with the parent MASTER.
  2530. Valid resource names: activebackground, activeforeground, anchor,
  2531. background, bd, bg, bitmap, borderwidth, command, cursor,
  2532. disabledforeground, fg, font, foreground, height,
  2533. highlightbackground, highlightcolor, highlightthickness, image,
  2534. indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
  2535. state, takefocus, text, textvariable, underline, value, variable,
  2536. width, wraplength."""
  2537. Widget.__init__(self, master, 'radiobutton', cnf, kw)
  2538. def deselect(self):
  2539. """Put the button in off-state."""
  2540. self.tk.call(self._w, 'deselect')
  2541. def flash(self):
  2542. """Flash the button."""
  2543. self.tk.call(self._w, 'flash')
  2544. def invoke(self):
  2545. """Toggle the button and invoke a command if given as resource."""
  2546. return self.tk.call(self._w, 'invoke')
  2547. def select(self):
  2548. """Put the button in on-state."""
  2549. self.tk.call(self._w, 'select')
  2550. class Scale(Widget):
  2551. """Scale widget which can display a numerical scale."""
  2552. def __init__(self, master=None, cnf={}, **kw):
  2553. """Construct a scale widget with the parent MASTER.
  2554. Valid resource names: activebackground, background, bigincrement, bd,
  2555. bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
  2556. highlightbackground, highlightcolor, highlightthickness, label,
  2557. length, orient, relief, repeatdelay, repeatinterval, resolution,
  2558. showvalue, sliderlength, sliderrelief, state, takefocus,
  2559. tickinterval, to, troughcolor, variable, width."""
  2560. Widget.__init__(self, master, 'scale', cnf, kw)
  2561. def get(self):
  2562. """Get the current value as integer or float."""
  2563. value = self.tk.call(self._w, 'get')
  2564. try:
  2565. return getint(value)
  2566. except ValueError:
  2567. return getdouble(value)
  2568. def set(self, value):
  2569. """Set the value to VALUE."""
  2570. self.tk.call(self._w, 'set', value)
  2571. def coords(self, value=None):
  2572. """Return a tuple (X,Y) of the point along the centerline of the
  2573. trough that corresponds to VALUE or the current value if None is
  2574. given."""
  2575. return self._getints(self.tk.call(self._w, 'coords', value))
  2576. def identify(self, x, y):
  2577. """Return where the point X,Y lies. Valid return values are "slider",
  2578. "though1" and "though2"."""
  2579. return self.tk.call(self._w, 'identify', x, y)
  2580. class Scrollbar(Widget):
  2581. """Scrollbar widget which displays a slider at a certain position."""
  2582. def __init__(self, master=None, cnf={}, **kw):
  2583. """Construct a scrollbar widget with the parent MASTER.
  2584. Valid resource names: activebackground, activerelief,
  2585. background, bd, bg, borderwidth, command, cursor,
  2586. elementborderwidth, highlightbackground,
  2587. highlightcolor, highlightthickness, jump, orient,
  2588. relief, repeatdelay, repeatinterval, takefocus,
  2589. troughcolor, width."""
  2590. Widget.__init__(self, master, 'scrollbar', cnf, kw)
  2591. def activate(self, index):
  2592. """Display the element at INDEX with activebackground and activerelief.
  2593. INDEX can be "arrow1","slider" or "arrow2"."""
  2594. self.tk.call(self._w, 'activate', index)
  2595. def delta(self, deltax, deltay):
  2596. """Return the fractional change of the scrollbar setting if it
  2597. would be moved by DELTAX or DELTAY pixels."""
  2598. return getdouble(
  2599. self.tk.call(self._w, 'delta', deltax, deltay))
  2600. def fraction(self, x, y):
  2601. """Return the fractional value which corresponds to a slider
  2602. position of X,Y."""
  2603. return getdouble(self.tk.call(self._w, 'fraction', x, y))
  2604. def identify(self, x, y):
  2605. """Return the element under position X,Y as one of
  2606. "arrow1","slider","arrow2" or ""."""
  2607. return self.tk.call(self._w, 'identify', x, y)
  2608. def get(self):
  2609. """Return the current fractional values (upper and lower end)
  2610. of the slider position."""
  2611. return self._getdoubles(self.tk.call(self._w, 'get'))
  2612. def set(self, *args):
  2613. """Set the fractional values of the slider position (upper and
  2614. lower ends as value between 0 and 1)."""
  2615. self.tk.call((self._w, 'set') + args)
  2616. class Text(Widget):
  2617. """Text widget which can display text in various forms."""
  2618. def __init__(self, master=None, cnf={}, **kw):
  2619. """Construct a text widget with the parent MASTER.
  2620. STANDARD OPTIONS
  2621. background, borderwidth, cursor,
  2622. exportselection, font, foreground,
  2623. highlightbackground, highlightcolor,
  2624. highlightthickness, insertbackground,
  2625. insertborderwidth, insertofftime,
  2626. insertontime, insertwidth, padx, pady,
  2627. relief, selectbackground,
  2628. selectborderwidth, selectforeground,
  2629. setgrid, takefocus,
  2630. xscrollcommand, yscrollcommand,
  2631. WIDGET-SPECIFIC OPTIONS
  2632. autoseparators, height, maxundo,
  2633. spacing1, spacing2, spacing3,
  2634. state, tabs, undo, width, wrap,
  2635. """
  2636. Widget.__init__(self, master, 'text', cnf, kw)
  2637. def bbox(self, *args):
  2638. """Return a tuple of (x,y,width,height) which gives the bounding
  2639. box of the visible part of the character at the index in ARGS."""
  2640. return self._getints(
  2641. self.tk.call((self._w, 'bbox') + args)) or None
  2642. def tk_textSelectTo(self, index):
  2643. self.tk.call('tk_textSelectTo', self._w, index)
  2644. def tk_textBackspace(self):
  2645. self.tk.call('tk_textBackspace', self._w)
  2646. def tk_textIndexCloser(self, a, b, c):
  2647. self.tk.call('tk_textIndexCloser', self._w, a, b, c)
  2648. def tk_textResetAnchor(self, index):
  2649. self.tk.call('tk_textResetAnchor', self._w, index)
  2650. def compare(self, index1, op, index2):
  2651. """Return whether between index INDEX1 and index INDEX2 the
  2652. relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
  2653. return self.tk.getboolean(self.tk.call(
  2654. self._w, 'compare', index1, op, index2))
  2655. def debug(self, boolean=None):
  2656. """Turn on the internal consistency checks of the B-Tree inside the text
  2657. widget according to BOOLEAN."""
  2658. return self.tk.getboolean(self.tk.call(
  2659. self._w, 'debug', boolean))
  2660. def delete(self, index1, index2=None):
  2661. """Delete the characters between INDEX1 and INDEX2 (not included)."""
  2662. self.tk.call(self._w, 'delete', index1, index2)
  2663. def dlineinfo(self, index):
  2664. """Return tuple (x,y,width,height,baseline) giving the bounding box
  2665. and baseline position of the visible part of the line containing
  2666. the character at INDEX."""
  2667. return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  2668. def dump(self, index1, index2=None, command=None, **kw):
  2669. """Return the contents of the widget between index1 and index2.
  2670. The type of contents returned in filtered based on the keyword
  2671. parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
  2672. given and true, then the corresponding items are returned. The result
  2673. is a list of triples of the form (key, value, index). If none of the
  2674. keywords are true then 'all' is used by default.
  2675. If the 'command' argument is given, it is called once for each element
  2676. of the list of triples, with the values of each triple serving as the
  2677. arguments to the function. In this case the list is not returned."""
  2678. args = []
  2679. func_name = None
  2680. result = None
  2681. if not command:
  2682. # Never call the dump command without the -command flag, since the
  2683. # output could involve Tcl quoting and would be a pain to parse
  2684. # right. Instead just set the command to build a list of triples
  2685. # as if we had done the parsing.
  2686. result = []
  2687. def append_triple(key, value, index, result=result):
  2688. result.append((key, value, index))
  2689. command = append_triple
  2690. try:
  2691. if not isinstance(command, str):
  2692. func_name = command = self._register(command)
  2693. args += ["-command", command]
  2694. for key in kw:
  2695. if kw[key]: args.append("-" + key)
  2696. args.append(index1)
  2697. if index2:
  2698. args.append(index2)
  2699. self.tk.call(self._w, "dump", *args)
  2700. return result
  2701. finally:
  2702. if func_name:
  2703. self.deletecommand(func_name)
  2704. ## new in tk8.4
  2705. def edit(self, *args):
  2706. """Internal method
  2707. This method controls the undo mechanism and
  2708. the modified flag. The exact behavior of the
  2709. command depends on the option argument that
  2710. follows the edit argument. The following forms
  2711. of the command are currently supported:
  2712. edit_modified, edit_redo, edit_reset, edit_separator
  2713. and edit_undo
  2714. """
  2715. return self.tk.call(self._w, 'edit', *args)
  2716. def edit_modified(self, arg=None):
  2717. """Get or Set the modified flag
  2718. If arg is not specified, returns the modified
  2719. flag of the widget. The insert, delete, edit undo and
  2720. edit redo commands or the user can set or clear the
  2721. modified flag. If boolean is specified, sets the
  2722. modified flag of the widget to arg.
  2723. """
  2724. return self.edit("modified", arg)
  2725. def edit_redo(self):
  2726. """Redo the last undone edit
  2727. When the undo option is true, reapplies the last
  2728. undone edits provided no other edits were done since
  2729. then. Generates an error when the redo stack is empty.
  2730. Does nothing when the undo option is false.
  2731. """
  2732. return self.edit("redo")
  2733. def edit_reset(self):
  2734. """Clears the undo and redo stacks
  2735. """
  2736. return self.edit("reset")
  2737. def edit_separator(self):
  2738. """Inserts a separator (boundary) on the undo stack.
  2739. Does nothing when the undo option is false
  2740. """
  2741. return self.edit("separator")
  2742. def edit_undo(self):
  2743. """Undoes the last edit action
  2744. If the undo option is true. An edit action is defined
  2745. as all the insert and delete commands that are recorded
  2746. on the undo stack in between two separators. Generates
  2747. an error when the undo stack is empty. Does nothing
  2748. when the undo option is false
  2749. """
  2750. return self.edit("undo")
  2751. def get(self, index1, index2=None):
  2752. """Return the text from INDEX1 to INDEX2 (not included)."""
  2753. return self.tk.call(self._w, 'get', index1, index2)
  2754. # (Image commands are new in 8.0)
  2755. def image_cget(self, index, option):
  2756. """Return the value of OPTION of an embedded image at INDEX."""
  2757. if option[:1] != "-":
  2758. option = "-" + option
  2759. if option[-1:] == "_":
  2760. option = option[:-1]
  2761. return self.tk.call(self._w, "image", "cget", index, option)
  2762. def image_configure(self, index, cnf=None, **kw):
  2763. """Configure an embedded image at INDEX."""
  2764. return self._configure(('image', 'configure', index), cnf, kw)
  2765. def image_create(self, index, cnf={}, **kw):
  2766. """Create an embedded image at INDEX."""
  2767. return self.tk.call(
  2768. self._w, "image", "create", index,
  2769. *self._options(cnf, kw))
  2770. def image_names(self):
  2771. """Return all names of embedded images in this widget."""
  2772. return self.tk.call(self._w, "image", "names")
  2773. def index(self, index):
  2774. """Return the index in the form line.char for INDEX."""
  2775. return str(self.tk.call(self._w, 'index', index))
  2776. def insert(self, index, chars, *args):
  2777. """Insert CHARS before the characters at INDEX. An additional
  2778. tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
  2779. self.tk.call((self._w, 'insert', index, chars) + args)
  2780. def mark_gravity(self, markName, direction=None):
  2781. """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
  2782. Return the current value if None is given for DIRECTION."""
  2783. return self.tk.call(
  2784. (self._w, 'mark', 'gravity', markName, direction))
  2785. def mark_names(self):
  2786. """Return all mark names."""
  2787. return self.tk.splitlist(self.tk.call(
  2788. self._w, 'mark', 'names'))
  2789. def mark_set(self, markName, index):
  2790. """Set mark MARKNAME before the character at INDEX."""
  2791. self.tk.call(self._w, 'mark', 'set', markName, index)
  2792. def mark_unset(self, *markNames):
  2793. """Delete all marks in MARKNAMES."""
  2794. self.tk.call((self._w, 'mark', 'unset') + markNames)
  2795. def mark_next(self, index):
  2796. """Return the name of the next mark after INDEX."""
  2797. return self.tk.call(self._w, 'mark', 'next', index) or None
  2798. def mark_previous(self, index):
  2799. """Return the name of the previous mark before INDEX."""
  2800. return self.tk.call(self._w, 'mark', 'previous', index) or None
  2801. def scan_mark(self, x, y):
  2802. """Remember the current X, Y coordinates."""
  2803. self.tk.call(self._w, 'scan', 'mark', x, y)
  2804. def scan_dragto(self, x, y):
  2805. """Adjust the view of the text to 10 times the
  2806. difference between X and Y and the coordinates given in
  2807. scan_mark."""
  2808. self.tk.call(self._w, 'scan', 'dragto', x, y)
  2809. def search(self, pattern, index, stopindex=None,
  2810. forwards=None, backwards=None, exact=None,
  2811. regexp=None, nocase=None, count=None, elide=None):
  2812. """Search PATTERN beginning from INDEX until STOPINDEX.
  2813. Return the index of the first character of a match or an
  2814. empty string."""
  2815. args = [self._w, 'search']
  2816. if forwards: args.append('-forwards')
  2817. if backwards: args.append('-backwards')
  2818. if exact: args.append('-exact')
  2819. if regexp: args.append('-regexp')
  2820. if nocase: args.append('-nocase')
  2821. if elide: args.append('-elide')
  2822. if count: args.append('-count'); args.append(count)
  2823. if pattern and pattern[0] == '-': args.append('--')
  2824. args.append(pattern)
  2825. args.append(index)
  2826. if stopindex: args.append(stopindex)
  2827. return str(self.tk.call(tuple(args)))
  2828. def see(self, index):
  2829. """Scroll such that the character at INDEX is visible."""
  2830. self.tk.call(self._w, 'see', index)
  2831. def tag_add(self, tagName, index1, *args):
  2832. """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
  2833. Additional pairs of indices may follow in ARGS."""
  2834. self.tk.call(
  2835. (self._w, 'tag', 'add', tagName, index1) + args)
  2836. def tag_unbind(self, tagName, sequence, funcid=None):
  2837. """Unbind for all characters with TAGNAME for event SEQUENCE the
  2838. function identified with FUNCID."""
  2839. self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  2840. if funcid:
  2841. self.deletecommand(funcid)
  2842. def tag_bind(self, tagName, sequence, func, add=None):
  2843. """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
  2844. An additional boolean parameter ADD specifies whether FUNC will be
  2845. called additionally to the other bound function or whether it will
  2846. replace the previous function. See bind for the return value."""
  2847. return self._bind((self._w, 'tag', 'bind', tagName),
  2848. sequence, func, add)
  2849. def tag_cget(self, tagName, option):
  2850. """Return the value of OPTION for tag TAGNAME."""
  2851. if option[:1] != '-':
  2852. option = '-' + option
  2853. if option[-1:] == '_':
  2854. option = option[:-1]
  2855. return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  2856. def tag_configure(self, tagName, cnf=None, **kw):
  2857. """Configure a tag TAGNAME."""
  2858. return self._configure(('tag', 'configure', tagName), cnf, kw)
  2859. tag_config = tag_configure
  2860. def tag_delete(self, *tagNames):
  2861. """Delete all tags in TAGNAMES."""
  2862. self.tk.call((self._w, 'tag', 'delete') + tagNames)
  2863. def tag_lower(self, tagName, belowThis=None):
  2864. """Change the priority of tag TAGNAME such that it is lower
  2865. than the priority of BELOWTHIS."""
  2866. self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  2867. def tag_names(self, index=None):
  2868. """Return a list of all tag names."""
  2869. return self.tk.splitlist(
  2870. self.tk.call(self._w, 'tag', 'names', index))
  2871. def tag_nextrange(self, tagName, index1, index2=None):
  2872. """Return a list of start and end index for the first sequence of
  2873. characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  2874. The text is searched forward from INDEX1."""
  2875. return self.tk.splitlist(self.tk.call(
  2876. self._w, 'tag', 'nextrange', tagName, index1, index2))
  2877. def tag_prevrange(self, tagName, index1, index2=None):
  2878. """Return a list of start and end index for the first sequence of
  2879. characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  2880. The text is searched backwards from INDEX1."""
  2881. return self.tk.splitlist(self.tk.call(
  2882. self._w, 'tag', 'prevrange', tagName, index1, index2))
  2883. def tag_raise(self, tagName, aboveThis=None):
  2884. """Change the priority of tag TAGNAME such that it is higher
  2885. than the priority of ABOVETHIS."""
  2886. self.tk.call(
  2887. self._w, 'tag', 'raise', tagName, aboveThis)
  2888. def tag_ranges(self, tagName):
  2889. """Return a list of ranges of text which have tag TAGNAME."""
  2890. return self.tk.splitlist(self.tk.call(
  2891. self._w, 'tag', 'ranges', tagName))
  2892. def tag_remove(self, tagName, index1, index2=None):
  2893. """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
  2894. self.tk.call(
  2895. self._w, 'tag', 'remove', tagName, index1, index2)
  2896. def window_cget(self, index, option):
  2897. """Return the value of OPTION of an embedded window at INDEX."""
  2898. if option[:1] != '-':
  2899. option = '-' + option
  2900. if option[-1:] == '_':
  2901. option = option[:-1]
  2902. return self.tk.call(self._w, 'window', 'cget', index, option)
  2903. def window_configure(self, index, cnf=None, **kw):
  2904. """Configure an embedded window at INDEX."""
  2905. return self._configure(('window', 'configure', index), cnf, kw)
  2906. window_config = window_configure
  2907. def window_create(self, index, cnf={}, **kw):
  2908. """Create a window at INDEX."""
  2909. self.tk.call(
  2910. (self._w, 'window', 'create', index)
  2911. + self._options(cnf, kw))
  2912. def window_names(self):
  2913. """Return all names of embedded windows in this widget."""
  2914. return self.tk.splitlist(
  2915. self.tk.call(self._w, 'window', 'names'))
  2916. def xview(self, *what):
  2917. """Query and change horizontal position of the view."""
  2918. if not what:
  2919. return self._getdoubles(self.tk.call(self._w, 'xview'))
  2920. self.tk.call((self._w, 'xview') + what)
  2921. def xview_moveto(self, fraction):
  2922. """Adjusts the view in the window so that FRACTION of the
  2923. total width of the canvas is off-screen to the left."""
  2924. self.tk.call(self._w, 'xview', 'moveto', fraction)
  2925. def xview_scroll(self, number, what):
  2926. """Shift the x-view according to NUMBER which is measured
  2927. in "units" or "pages" (WHAT)."""
  2928. self.tk.call(self._w, 'xview', 'scroll', number, what)
  2929. def yview(self, *what):
  2930. """Query and change vertical position of the view."""
  2931. if not what:
  2932. return self._getdoubles(self.tk.call(self._w, 'yview'))
  2933. self.tk.call((self._w, 'yview') + what)
  2934. def yview_moveto(self, fraction):
  2935. """Adjusts the view in the window so that FRACTION of the
  2936. total height of the canvas is off-screen to the top."""
  2937. self.tk.call(self._w, 'yview', 'moveto', fraction)
  2938. def yview_scroll(self, number, what):
  2939. """Shift the y-view according to NUMBER which is measured
  2940. in "units" or "pages" (WHAT)."""
  2941. self.tk.call(self._w, 'yview', 'scroll', number, what)
  2942. def yview_pickplace(self, *what):
  2943. """Obsolete function, use see."""
  2944. self.tk.call((self._w, 'yview', '-pickplace') + what)
  2945. class _setit:
  2946. """Internal class. It wraps the command in the widget OptionMenu."""
  2947. def __init__(self, var, value, callback=None):
  2948. self.__value = value
  2949. self.__var = var
  2950. self.__callback = callback
  2951. def __call__(self, *args):
  2952. self.__var.set(self.__value)
  2953. if self.__callback:
  2954. self.__callback(self.__value, *args)
  2955. class OptionMenu(Menubutton):
  2956. """OptionMenu which allows the user to select a value from a menu."""
  2957. def __init__(self, master, variable, value, *values, **kwargs):
  2958. """Construct an optionmenu widget with the parent MASTER, with
  2959. the resource textvariable set to VARIABLE, the initially selected
  2960. value VALUE, the other menu values VALUES and an additional
  2961. keyword argument command."""
  2962. kw = {"borderwidth": 2, "textvariable": variable,
  2963. "indicatoron": 1, "relief": RAISED, "anchor": "c",
  2964. "highlightthickness": 2}
  2965. Widget.__init__(self, master, "menubutton", kw)
  2966. self.widgetName = 'tk_optionMenu'
  2967. menu = self.__menu = Menu(self, name="menu", tearoff=0)
  2968. self.menuname = menu._w
  2969. # 'command' is the only supported keyword
  2970. callback = kwargs.get('command')
  2971. if kwargs.has_key('command'):
  2972. del kwargs['command']
  2973. if kwargs:
  2974. raise TclError, 'unknown option -'+kwargs.keys()[0]
  2975. menu.add_command(label=value,
  2976. command=_setit(variable, value, callback))
  2977. for v in values:
  2978. menu.add_command(label=v,
  2979. command=_setit(variable, v, callback))
  2980. self["menu"] = menu
  2981. def __getitem__(self, name):
  2982. if name == 'menu':
  2983. return self.__menu
  2984. return Widget.__getitem__(self, name)
  2985. def destroy(self):
  2986. """Destroy this widget and the associated menu."""
  2987. Menubutton.destroy(self)
  2988. self.__menu = None
  2989. class Image:
  2990. """Base class for images."""
  2991. _last_id = 0
  2992. def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
  2993. self.name = None
  2994. if not master:
  2995. master = _default_root
  2996. if not master:
  2997. raise RuntimeError, 'Too early to create image'
  2998. self.tk = master.tk
  2999. if not name:
  3000. Image._last_id += 1
  3001. name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
  3002. # The following is needed for systems where id(x)
  3003. # can return a negative number, such as Linux/m68k:
  3004. if name[0] == '-': name = '_' + name[1:]
  3005. if kw and cnf: cnf = _cnfmerge((cnf, kw))
  3006. elif kw: cnf = kw
  3007. options = ()
  3008. for k, v in cnf.items():
  3009. if callable(v):
  3010. v = self._register(v)
  3011. options = options + ('-'+k, v)
  3012. self.tk.call(('image', 'create', imgtype, name,) + options)
  3013. self.name = name
  3014. def __str__(self): return self.name
  3015. def __del__(self):
  3016. if self.name:
  3017. try:
  3018. self.tk.call('image', 'delete', self.name)
  3019. except TclError:
  3020. # May happen if the root was destroyed
  3021. pass
  3022. def __setitem__(self, key, value):
  3023. self.tk.call(self.name, 'configure', '-'+key, value)
  3024. def __getitem__(self, key):
  3025. return self.tk.call(self.name, 'configure', '-'+key)
  3026. def configure(self, **kw):
  3027. """Configure the image."""
  3028. res = ()
  3029. for k, v in _cnfmerge(kw).items():
  3030. if v is not None:
  3031. if k[-1] == '_': k = k[:-1]
  3032. if callable(v):
  3033. v = self._register(v)
  3034. res = res + ('-'+k, v)
  3035. self.tk.call((self.name, 'config') + res)
  3036. config = configure
  3037. def height(self):
  3038. """Return the height of the image."""
  3039. return getint(
  3040. self.tk.call('image', 'height', self.name))
  3041. def type(self):
  3042. """Return the type of the imgage, e.g. "photo" or "bitmap"."""
  3043. return self.tk.call('image', 'type', self.name)
  3044. def width(self):
  3045. """Return the width of the image."""
  3046. return getint(
  3047. self.tk.call('image', 'width', self.name))
  3048. class PhotoImage(Image):
  3049. """Widget which can display colored images in GIF, PPM/PGM format."""
  3050. def __init__(self, name=None, cnf={}, master=None, **kw):
  3051. """Create an image with NAME.
  3052. Valid resource names: data, format, file, gamma, height, palette,
  3053. width."""
  3054. Image.__init__(self, 'photo', name, cnf, master, **kw)
  3055. def blank(self):
  3056. """Display a transparent image."""
  3057. self.tk.call(self.name, 'blank')
  3058. def cget(self, option):
  3059. """Return the value of OPTION."""
  3060. return self.tk.call(self.name, 'cget', '-' + option)
  3061. # XXX config
  3062. def __getitem__(self, key):
  3063. return self.tk.call(self.name, 'cget', '-' + key)
  3064. # XXX copy -from, -to, ...?
  3065. def copy(self):
  3066. """Return a new PhotoImage with the same image as this widget."""
  3067. destImage = PhotoImage()
  3068. self.tk.call(destImage, 'copy', self.name)
  3069. return destImage
  3070. def zoom(self,x,y=''):
  3071. """Return a new PhotoImage with the same image as this widget
  3072. but zoom it with X and Y."""
  3073. destImage = PhotoImage()
  3074. if y=='': y=x
  3075. self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
  3076. return destImage
  3077. def subsample(self,x,y=''):
  3078. """Return a new PhotoImage based on the same image as this widget
  3079. but use only every Xth or Yth pixel."""
  3080. destImage = PhotoImage()
  3081. if y=='': y=x
  3082. self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
  3083. return destImage
  3084. def get(self, x, y):
  3085. """Return the color (red, green, blue) of the pixel at X,Y."""
  3086. return self.tk.call(self.name, 'get', x, y)
  3087. def put(self, data, to=None):
  3088. """Put row formatted colors to image starting from
  3089. position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
  3090. args = (self.name, 'put', data)
  3091. if to:
  3092. if to[0] == '-to':
  3093. to = to[1:]
  3094. args = args + ('-to',) + tuple(to)
  3095. self.tk.call(args)
  3096. # XXX read
  3097. def write(self, filename, format=None, from_coords=None):
  3098. """Write image to file FILENAME in FORMAT starting from
  3099. position FROM_COORDS."""
  3100. args = (self.name, 'write', filename)
  3101. if format:
  3102. args = args + ('-format', format)
  3103. if from_coords:
  3104. args = args + ('-from',) + tuple(from_coords)
  3105. self.tk.call(args)
  3106. class BitmapImage(Image):
  3107. """Widget which can display a bitmap."""
  3108. def __init__(self, name=None, cnf={}, master=None, **kw):
  3109. """Create a bitmap with NAME.
  3110. Valid resource names: background, data, file, foreground, maskdata, maskfile."""
  3111. Image.__init__(self, 'bitmap', name, cnf, master, **kw)
  3112. def image_names(): return _default_root.tk.call('image', 'names')
  3113. def image_types(): return _default_root.tk.call('image', 'types')
  3114. class Spinbox(Widget):
  3115. """spinbox widget."""
  3116. def __init__(self, master=None, cnf={}, **kw):
  3117. """Construct a spinbox widget with the parent MASTER.
  3118. STANDARD OPTIONS
  3119. activebackground, background, borderwidth,
  3120. cursor, exportselection, font, foreground,
  3121. highlightbackground, highlightcolor,
  3122. highlightthickness, insertbackground,
  3123. insertborderwidth, insertofftime,
  3124. insertontime, insertwidth, justify, relief,
  3125. repeatdelay, repeatinterval,
  3126. selectbackground, selectborderwidth
  3127. selectforeground, takefocus, textvariable
  3128. xscrollcommand.
  3129. WIDGET-SPECIFIC OPTIONS
  3130. buttonbackground, buttoncursor,
  3131. buttondownrelief, buttonuprelief,
  3132. command, disabledbackground,
  3133. disabledforeground, format, from,
  3134. invalidcommand, increment,
  3135. readonlybackground, state, to,
  3136. validate, validatecommand values,
  3137. width, wrap,
  3138. """
  3139. Widget.__init__(self, master, 'spinbox', cnf, kw)
  3140. def bbox(self, index):
  3141. """Return a tuple of X1,Y1,X2,Y2 coordinates for a
  3142. rectangle which encloses the character given by index.
  3143. The first two elements of the list give the x and y
  3144. coordinates of the upper-left corner of the screen
  3145. area covered by the character (in pixels relative
  3146. to the widget) and the last two elements give the
  3147. width and height of the character, in pixels. The
  3148. bounding box may refer to a region outside the
  3149. visible area of the window.
  3150. """
  3151. return self.tk.call(self._w, 'bbox', index)
  3152. def delete(self, first, last=None):
  3153. """Delete one or more elements of the spinbox.
  3154. First is the index of the first character to delete,
  3155. and last is the index of the character just after
  3156. the last one to delete. If last isn't specified it
  3157. defaults to first+1, i.e. a single character is
  3158. deleted. This command returns an empty string.
  3159. """
  3160. return self.tk.call(self._w, 'delete', first, last)
  3161. def get(self):
  3162. """Returns the spinbox's string"""
  3163. return self.tk.call(self._w, 'get')
  3164. def icursor(self, index):
  3165. """Alter the position of the insertion cursor.
  3166. The insertion cursor will be displayed just before
  3167. the character given by index. Returns an empty string
  3168. """
  3169. return self.tk.call(self._w, 'icursor', index)
  3170. def identify(self, x, y):
  3171. """Returns the name of the widget at position x, y
  3172. Return value is one of: none, buttondown, buttonup, entry
  3173. """
  3174. return self.tk.call(self._w, 'identify', x, y)
  3175. def index(self, index):
  3176. """Returns the numerical index corresponding to index
  3177. """
  3178. return self.tk.call(self._w, 'index', index)
  3179. def insert(self, index, s):
  3180. """Insert string s at index
  3181. Returns an empty string.
  3182. """
  3183. return self.tk.call(self._w, 'insert', index, s)
  3184. def invoke(self, element):
  3185. """Causes the specified element to be invoked
  3186. The element could be buttondown or buttonup
  3187. triggering the action associated with it.
  3188. """
  3189. return self.tk.call(self._w, 'invoke', element)
  3190. def scan(self, *args):
  3191. """Internal function."""
  3192. return self._getints(
  3193. self.tk.call((self._w, 'scan') + args)) or ()
  3194. def scan_mark(self, x):
  3195. """Records x and the current view in the spinbox window;
  3196. used in conjunction with later scan dragto commands.
  3197. Typically this command is associated with a mouse button
  3198. press in the widget. It returns an empty string.
  3199. """
  3200. return self.scan("mark", x)
  3201. def scan_dragto(self, x):
  3202. """Compute the difference between the given x argument
  3203. and the x argument to the last scan mark command
  3204. It then adjusts the view left or right by 10 times the
  3205. difference in x-coordinates. This command is typically
  3206. associated with mouse motion events in the widget, to
  3207. produce the effect of dragging the spinbox at high speed
  3208. through the window. The return value is an empty string.
  3209. """
  3210. return self.scan("dragto", x)
  3211. def selection(self, *args):
  3212. """Internal function."""
  3213. return self._getints(
  3214. self.tk.call((self._w, 'selection') + args)) or ()
  3215. def selection_adjust(self, index):
  3216. """Locate the end of the selection nearest to the character
  3217. given by index,
  3218. Then adjust that end of the selection to be at index
  3219. (i.e including but not going beyond index). The other
  3220. end of the selection is made the anchor point for future
  3221. select to commands. If the selection isn't currently in
  3222. the spinbox, then a new selection is created to include
  3223. the characters between index and the most recent selection
  3224. anchor point, inclusive. Returns an empty string.
  3225. """
  3226. return self.selection("adjust", index)
  3227. def selection_clear(self):
  3228. """Clear the selection
  3229. If the selection isn't in this widget then the
  3230. command has no effect. Returns an empty string.
  3231. """
  3232. return self.selection("clear")
  3233. def selection_element(self, element=None):
  3234. """Sets or gets the currently selected element.
  3235. If a spinbutton element is specified, it will be
  3236. displayed depressed
  3237. """
  3238. return self.selection("element", element)
  3239. ###########################################################################
  3240. class LabelFrame(Widget):
  3241. """labelframe widget."""
  3242. def __init__(self, master=None, cnf={}, **kw):
  3243. """Construct a labelframe widget with the parent MASTER.
  3244. STANDARD OPTIONS
  3245. borderwidth, cursor, font, foreground,
  3246. highlightbackground, highlightcolor,
  3247. highlightthickness, padx, pady, relief,
  3248. takefocus, text
  3249. WIDGET-SPECIFIC OPTIONS
  3250. background, class, colormap, container,
  3251. height, labelanchor, labelwidget,
  3252. visual, width
  3253. """
  3254. Widget.__init__(self, master, 'labelframe', cnf, kw)
  3255. ########################################################################
  3256. class PanedWindow(Widget):
  3257. """panedwindow widget."""
  3258. def __init__(self, master=None, cnf={}, **kw):
  3259. """Construct a panedwindow widget with the parent MASTER.
  3260. STANDARD OPTIONS
  3261. background, borderwidth, cursor, height,
  3262. orient, relief, width
  3263. WIDGET-SPECIFIC OPTIONS
  3264. handlepad, handlesize, opaqueresize,
  3265. sashcursor, sashpad, sashrelief,
  3266. sashwidth, showhandle,
  3267. """
  3268. Widget.__init__(self, master, 'panedwindow', cnf, kw)
  3269. def add(self, child, **kw):
  3270. """Add a child widget to the panedwindow in a new pane.
  3271. The child argument is the name of the child widget
  3272. followed by pairs of arguments that specify how to
  3273. manage the windows. Options may have any of the values
  3274. accepted by the configure subcommand.
  3275. """
  3276. self.tk.call((self._w, 'add', child) + self._options(kw))
  3277. def remove(self, child):
  3278. """Remove the pane containing child from the panedwindow
  3279. All geometry management options for child will be forgotten.
  3280. """
  3281. self.tk.call(self._w, 'forget', child)
  3282. forget=remove
  3283. def identify(self, x, y):
  3284. """Identify the panedwindow component at point x, y
  3285. If the point is over a sash or a sash handle, the result
  3286. is a two element list containing the index of the sash or
  3287. handle, and a word indicating whether it is over a sash
  3288. or a handle, such as {0 sash} or {2 handle}. If the point
  3289. is over any other part of the panedwindow, the result is
  3290. an empty list.
  3291. """
  3292. return self.tk.call(self._w, 'identify', x, y)
  3293. def proxy(self, *args):
  3294. """Internal function."""
  3295. return self._getints(
  3296. self.tk.call((self._w, 'proxy') + args)) or ()
  3297. def proxy_coord(self):
  3298. """Return the x and y pair of the most recent proxy location
  3299. """
  3300. return self.proxy("coord")
  3301. def proxy_forget(self):
  3302. """Remove the proxy from the display.
  3303. """
  3304. return self.proxy("forget")
  3305. def proxy_place(self, x, y):
  3306. """Place the proxy at the given x and y coordinates.
  3307. """
  3308. return self.proxy("place", x, y)
  3309. def sash(self, *args):
  3310. """Internal function."""
  3311. return self._getints(
  3312. self.tk.call((self._w, 'sash') + args)) or ()
  3313. def sash_coord(self, index):
  3314. """Return the current x and y pair for the sash given by index.
  3315. Index must be an integer between 0 and 1 less than the
  3316. number of panes in the panedwindow. The coordinates given are
  3317. those of the top left corner of the region containing the sash.
  3318. pathName sash dragto index x y This command computes the
  3319. difference between the given coordinates and the coordinates
  3320. given to the last sash coord command for the given sash. It then
  3321. moves that sash the computed difference. The return value is the
  3322. empty string.
  3323. """
  3324. return self.sash("coord", index)
  3325. def sash_mark(self, index):
  3326. """Records x and y for the sash given by index;
  3327. Used in conjunction with later dragto commands to move the sash.
  3328. """
  3329. return self.sash("mark", index)
  3330. def sash_place(self, index, x, y):
  3331. """Place the sash given by index at the given coordinates
  3332. """
  3333. return self.sash("place", index, x, y)
  3334. def panecget(self, child, option):
  3335. """Query a management option for window.
  3336. Option may be any value allowed by the paneconfigure subcommand
  3337. """
  3338. return self.tk.call(
  3339. (self._w, 'panecget') + (child, '-'+option))
  3340. def paneconfigure(self, tagOrId, cnf=None, **kw):
  3341. """Query or modify the management options for window.
  3342. If no option is specified, returns a list describing all
  3343. of the available options for pathName. If option is
  3344. specified with no value, then the command returns a list
  3345. describing the one named option (this list will be identical
  3346. to the corresponding sublist of the value returned if no
  3347. option is specified). If one or more option-value pairs are
  3348. specified, then the command modifies the given widget
  3349. option(s) to have the given value(s); in this case the
  3350. command returns an empty string. The following options
  3351. are supported:
  3352. after window
  3353. Insert the window after the window specified. window
  3354. should be the name of a window already managed by pathName.
  3355. before window
  3356. Insert the window before the window specified. window
  3357. should be the name of a window already managed by pathName.
  3358. height size
  3359. Specify a height for the window. The height will be the
  3360. outer dimension of the window including its border, if
  3361. any. If size is an empty string, or if -height is not
  3362. specified, then the height requested internally by the
  3363. window will be used initially; the height may later be
  3364. adjusted by the movement of sashes in the panedwindow.
  3365. Size may be any value accepted by Tk_GetPixels.
  3366. minsize n
  3367. Specifies that the size of the window cannot be made
  3368. less than n. This constraint only affects the size of
  3369. the widget in the paned dimension -- the x dimension
  3370. for horizontal panedwindows, the y dimension for
  3371. vertical panedwindows. May be any value accepted by
  3372. Tk_GetPixels.
  3373. padx n
  3374. Specifies a non-negative value indicating how much
  3375. extra space to leave on each side of the window in
  3376. the X-direction. The value may have any of the forms
  3377. accepted by Tk_GetPixels.
  3378. pady n
  3379. Specifies a non-negative value indicating how much
  3380. extra space to leave on each side of the window in
  3381. the Y-direction. The value may have any of the forms
  3382. accepted by Tk_GetPixels.
  3383. sticky style
  3384. If a window's pane is larger than the requested
  3385. dimensions of the window, this option may be used
  3386. to position (or stretch) the window within its pane.
  3387. Style is a string that contains zero or more of the
  3388. characters n, s, e or w. The string can optionally
  3389. contains spaces or commas, but they are ignored. Each
  3390. letter refers to a side (north, south, east, or west)
  3391. that the window will "stick" to. If both n and s
  3392. (or e and w) are specified, the window will be
  3393. stretched to fill the entire height (or width) of
  3394. its cavity.
  3395. width size
  3396. Specify a width for the window. The width will be
  3397. the outer dimension of the window including its
  3398. border, if any. If size is an empty string, or
  3399. if -width is not specified, then the width requested
  3400. internally by the window will be used initially; the
  3401. width may later be adjusted by the movement of sashes
  3402. in the panedwindow. Size may be any value accepted by
  3403. Tk_GetPixels.
  3404. """
  3405. if cnf is None and not kw:
  3406. cnf = {}
  3407. for x in self.tk.split(
  3408. self.tk.call(self._w,
  3409. 'paneconfigure', tagOrId)):
  3410. cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  3411. return cnf
  3412. if type(cnf) == StringType and not kw:
  3413. x = self.tk.split(self.tk.call(
  3414. self._w, 'paneconfigure', tagOrId, '-'+cnf))
  3415. return (x[0][1:],) + x[1:]
  3416. self.tk.call((self._w, 'paneconfigure', tagOrId) +
  3417. self._options(cnf, kw))
  3418. paneconfig = paneconfigure
  3419. def panes(self):
  3420. """Returns an ordered list of the child panes."""
  3421. return self.tk.call(self._w, 'panes')
  3422. ######################################################################
  3423. # Extensions:
  3424. class Studbutton(Button):
  3425. def __init__(self, master=None, cnf={}, **kw):
  3426. Widget.__init__(self, master, 'studbutton', cnf, kw)
  3427. self.bind('<Any-Enter>', self.tkButtonEnter)
  3428. self.bind('<Any-Leave>', self.tkButtonLeave)
  3429. self.bind('<1>', self.tkButtonDown)
  3430. self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3431. class Tributton(Button):
  3432. def __init__(self, master=None, cnf={}, **kw):
  3433. Widget.__init__(self, master, 'tributton', cnf, kw)
  3434. self.bind('<Any-Enter>', self.tkButtonEnter)
  3435. self.bind('<Any-Leave>', self.tkButtonLeave)
  3436. self.bind('<1>', self.tkButtonDown)
  3437. self.bind('<ButtonRelease-1>', self.tkButtonUp)
  3438. self['fg'] = self['bg']
  3439. self['activebackground'] = self['bg']
  3440. ######################################################################
  3441. # Test:
  3442. def _test():
  3443. root = Tk()
  3444. text = "This is Tcl/Tk version %s" % TclVersion
  3445. if TclVersion >= 8.1:
  3446. try:
  3447. text = text + unicode("\nThis should be a cedilla: \347",
  3448. "iso-8859-1")
  3449. except NameError:
  3450. pass # no unicode support
  3451. label = Label(root, text=text)
  3452. label.pack()
  3453. test = Button(root, text="Click me!",
  3454. command=lambda root=root: root.test.configure(
  3455. text="[%s]" % root.test['text']))
  3456. test.pack()
  3457. root.test = test
  3458. quit = Button(root, text="QUIT", command=root.destroy)
  3459. quit.pack()
  3460. # The following three commands are needed so the window pops
  3461. # up on top on Windows...
  3462. root.iconify()
  3463. root.update()
  3464. root.deiconify()
  3465. root.mainloop()
  3466. if __name__ == '__main__':
  3467. _test()