logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

__init__.py (170517B)


  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 tkinter.constants 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. import enum
  28. import sys
  29. import types
  30. import _tkinter # If this fails your Python may not be configured for Tk
  31. TclError = _tkinter.TclError
  32. from tkinter.constants import *
  33. import re
  34. wantobjects = 1
  35. TkVersion = float(_tkinter.TK_VERSION)
  36. TclVersion = float(_tkinter.TCL_VERSION)
  37. READABLE = _tkinter.READABLE
  38. WRITABLE = _tkinter.WRITABLE
  39. EXCEPTION = _tkinter.EXCEPTION
  40. _magic_re = re.compile(r'([\\{}])')
  41. _space_re = re.compile(r'([\s])', re.ASCII)
  42. def _join(value):
  43. """Internal function."""
  44. return ' '.join(map(_stringify, value))
  45. def _stringify(value):
  46. """Internal function."""
  47. if isinstance(value, (list, tuple)):
  48. if len(value) == 1:
  49. value = _stringify(value[0])
  50. if _magic_re.search(value):
  51. value = '{%s}' % value
  52. else:
  53. value = '{%s}' % _join(value)
  54. else:
  55. value = str(value)
  56. if not value:
  57. value = '{}'
  58. elif _magic_re.search(value):
  59. # add '\' before special characters and spaces
  60. value = _magic_re.sub(r'\\\1', value)
  61. value = value.replace('\n', r'\n')
  62. value = _space_re.sub(r'\\\1', value)
  63. if value[0] == '"':
  64. value = '\\' + value
  65. elif value[0] == '"' or _space_re.search(value):
  66. value = '{%s}' % value
  67. return value
  68. def _flatten(seq):
  69. """Internal function."""
  70. res = ()
  71. for item in seq:
  72. if isinstance(item, (tuple, list)):
  73. res = res + _flatten(item)
  74. elif item is not None:
  75. res = res + (item,)
  76. return res
  77. try: _flatten = _tkinter._flatten
  78. except AttributeError: pass
  79. def _cnfmerge(cnfs):
  80. """Internal function."""
  81. if isinstance(cnfs, dict):
  82. return cnfs
  83. elif isinstance(cnfs, (type(None), str)):
  84. return cnfs
  85. else:
  86. cnf = {}
  87. for c in _flatten(cnfs):
  88. try:
  89. cnf.update(c)
  90. except (AttributeError, TypeError) as msg:
  91. print("_cnfmerge: fallback due to:", msg)
  92. for k, v in c.items():
  93. cnf[k] = v
  94. return cnf
  95. try: _cnfmerge = _tkinter._cnfmerge
  96. except AttributeError: pass
  97. def _splitdict(tk, v, cut_minus=True, conv=None):
  98. """Return a properly formatted dict built from Tcl list pairs.
  99. If cut_minus is True, the supposed '-' prefix will be removed from
  100. keys. If conv is specified, it is used to convert values.
  101. Tcl list is expected to contain an even number of elements.
  102. """
  103. t = tk.splitlist(v)
  104. if len(t) % 2:
  105. raise RuntimeError('Tcl list representing a dict is expected '
  106. 'to contain an even number of elements')
  107. it = iter(t)
  108. dict = {}
  109. for key, value in zip(it, it):
  110. key = str(key)
  111. if cut_minus and key[0] == '-':
  112. key = key[1:]
  113. if conv:
  114. value = conv(value)
  115. dict[key] = value
  116. return dict
  117. class EventType(str, enum.Enum):
  118. KeyPress = '2'
  119. Key = KeyPress
  120. KeyRelease = '3'
  121. ButtonPress = '4'
  122. Button = ButtonPress
  123. ButtonRelease = '5'
  124. Motion = '6'
  125. Enter = '7'
  126. Leave = '8'
  127. FocusIn = '9'
  128. FocusOut = '10'
  129. Keymap = '11' # undocumented
  130. Expose = '12'
  131. GraphicsExpose = '13' # undocumented
  132. NoExpose = '14' # undocumented
  133. Visibility = '15'
  134. Create = '16'
  135. Destroy = '17'
  136. Unmap = '18'
  137. Map = '19'
  138. MapRequest = '20'
  139. Reparent = '21'
  140. Configure = '22'
  141. ConfigureRequest = '23'
  142. Gravity = '24'
  143. ResizeRequest = '25'
  144. Circulate = '26'
  145. CirculateRequest = '27'
  146. Property = '28'
  147. SelectionClear = '29' # undocumented
  148. SelectionRequest = '30' # undocumented
  149. Selection = '31' # undocumented
  150. Colormap = '32'
  151. ClientMessage = '33' # undocumented
  152. Mapping = '34' # undocumented
  153. VirtualEvent = '35' # undocumented
  154. Activate = '36'
  155. Deactivate = '37'
  156. MouseWheel = '38'
  157. __str__ = str.__str__
  158. class Event:
  159. """Container for the properties of an event.
  160. Instances of this type are generated if one of the following events occurs:
  161. KeyPress, KeyRelease - for keyboard events
  162. ButtonPress, ButtonRelease, Motion, Enter, Leave, MouseWheel - for mouse events
  163. Visibility, Unmap, Map, Expose, FocusIn, FocusOut, Circulate,
  164. Colormap, Gravity, Reparent, Property, Destroy, Activate,
  165. Deactivate - for window events.
  166. If a callback function for one of these events is registered
  167. using bind, bind_all, bind_class, or tag_bind, the callback is
  168. called with an Event as first argument. It will have the
  169. following attributes (in braces are the event types for which
  170. the attribute is valid):
  171. serial - serial number of event
  172. num - mouse button pressed (ButtonPress, ButtonRelease)
  173. focus - whether the window has the focus (Enter, Leave)
  174. height - height of the exposed window (Configure, Expose)
  175. width - width of the exposed window (Configure, Expose)
  176. keycode - keycode of the pressed key (KeyPress, KeyRelease)
  177. state - state of the event as a number (ButtonPress, ButtonRelease,
  178. Enter, KeyPress, KeyRelease,
  179. Leave, Motion)
  180. state - state as a string (Visibility)
  181. time - when the event occurred
  182. x - x-position of the mouse
  183. y - y-position of the mouse
  184. x_root - x-position of the mouse on the screen
  185. (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  186. y_root - y-position of the mouse on the screen
  187. (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
  188. char - pressed character (KeyPress, KeyRelease)
  189. send_event - see X/Windows documentation
  190. keysym - keysym of the event as a string (KeyPress, KeyRelease)
  191. keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
  192. type - type of the event as a number
  193. widget - widget in which the event occurred
  194. delta - delta of wheel movement (MouseWheel)
  195. """
  196. def __repr__(self):
  197. attrs = {k: v for k, v in self.__dict__.items() if v != '??'}
  198. if not self.char:
  199. del attrs['char']
  200. elif self.char != '??':
  201. attrs['char'] = repr(self.char)
  202. if not getattr(self, 'send_event', True):
  203. del attrs['send_event']
  204. if self.state == 0:
  205. del attrs['state']
  206. elif isinstance(self.state, int):
  207. state = self.state
  208. mods = ('Shift', 'Lock', 'Control',
  209. 'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5',
  210. 'Button1', 'Button2', 'Button3', 'Button4', 'Button5')
  211. s = []
  212. for i, n in enumerate(mods):
  213. if state & (1 << i):
  214. s.append(n)
  215. state = state & ~((1<< len(mods)) - 1)
  216. if state or not s:
  217. s.append(hex(state))
  218. attrs['state'] = '|'.join(s)
  219. if self.delta == 0:
  220. del attrs['delta']
  221. # widget usually is known
  222. # serial and time are not very interesting
  223. # keysym_num duplicates keysym
  224. # x_root and y_root mostly duplicate x and y
  225. keys = ('send_event',
  226. 'state', 'keysym', 'keycode', 'char',
  227. 'num', 'delta', 'focus',
  228. 'x', 'y', 'width', 'height')
  229. return '<%s event%s>' % (
  230. getattr(self.type, 'name', self.type),
  231. ''.join(' %s=%s' % (k, attrs[k]) for k in keys if k in attrs)
  232. )
  233. _support_default_root = True
  234. _default_root = None
  235. def NoDefaultRoot():
  236. """Inhibit setting of default root window.
  237. Call this function to inhibit that the first instance of
  238. Tk is used for windows without an explicit parent window.
  239. """
  240. global _support_default_root, _default_root
  241. _support_default_root = False
  242. # Delete, so any use of _default_root will immediately raise an exception.
  243. # Rebind before deletion, so repeated calls will not fail.
  244. _default_root = None
  245. del _default_root
  246. def _get_default_root(what=None):
  247. if not _support_default_root:
  248. raise RuntimeError("No master specified and tkinter is "
  249. "configured to not support default root")
  250. if _default_root is None:
  251. if what:
  252. raise RuntimeError(f"Too early to {what}: no default root window")
  253. root = Tk()
  254. assert _default_root is root
  255. return _default_root
  256. def _get_temp_root():
  257. global _support_default_root
  258. if not _support_default_root:
  259. raise RuntimeError("No master specified and tkinter is "
  260. "configured to not support default root")
  261. root = _default_root
  262. if root is None:
  263. assert _support_default_root
  264. _support_default_root = False
  265. root = Tk()
  266. _support_default_root = True
  267. assert _default_root is None
  268. root.withdraw()
  269. root._temporary = True
  270. return root
  271. def _destroy_temp_root(master):
  272. if getattr(master, '_temporary', False):
  273. try:
  274. master.destroy()
  275. except TclError:
  276. pass
  277. def _tkerror(err):
  278. """Internal function."""
  279. pass
  280. def _exit(code=0):
  281. """Internal function. Calling it will raise the exception SystemExit."""
  282. try:
  283. code = int(code)
  284. except ValueError:
  285. pass
  286. raise SystemExit(code)
  287. _varnum = 0
  288. class Variable:
  289. """Class to define value holders for e.g. buttons.
  290. Subclasses StringVar, IntVar, DoubleVar, BooleanVar are specializations
  291. that constrain the type of the value returned from get()."""
  292. _default = ""
  293. _tk = None
  294. _tclCommands = None
  295. def __init__(self, master=None, value=None, name=None):
  296. """Construct a variable
  297. MASTER can be given as master widget.
  298. VALUE is an optional value (defaults to "")
  299. NAME is an optional Tcl name (defaults to PY_VARnum).
  300. If NAME matches an existing variable and VALUE is omitted
  301. then the existing value is retained.
  302. """
  303. # check for type of NAME parameter to override weird error message
  304. # raised from Modules/_tkinter.c:SetVar like:
  305. # TypeError: setvar() takes exactly 3 arguments (2 given)
  306. if name is not None and not isinstance(name, str):
  307. raise TypeError("name must be a string")
  308. global _varnum
  309. if master is None:
  310. master = _get_default_root('create variable')
  311. self._root = master._root()
  312. self._tk = master.tk
  313. if name:
  314. self._name = name
  315. else:
  316. self._name = 'PY_VAR' + repr(_varnum)
  317. _varnum += 1
  318. if value is not None:
  319. self.initialize(value)
  320. elif not self._tk.getboolean(self._tk.call("info", "exists", self._name)):
  321. self.initialize(self._default)
  322. def __del__(self):
  323. """Unset the variable in Tcl."""
  324. if self._tk is None:
  325. return
  326. if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
  327. self._tk.globalunsetvar(self._name)
  328. if self._tclCommands is not None:
  329. for name in self._tclCommands:
  330. #print '- Tkinter: deleted command', name
  331. self._tk.deletecommand(name)
  332. self._tclCommands = None
  333. def __str__(self):
  334. """Return the name of the variable in Tcl."""
  335. return self._name
  336. def set(self, value):
  337. """Set the variable to VALUE."""
  338. return self._tk.globalsetvar(self._name, value)
  339. initialize = set
  340. def get(self):
  341. """Return value of variable."""
  342. return self._tk.globalgetvar(self._name)
  343. def _register(self, callback):
  344. f = CallWrapper(callback, None, self._root).__call__
  345. cbname = repr(id(f))
  346. try:
  347. callback = callback.__func__
  348. except AttributeError:
  349. pass
  350. try:
  351. cbname = cbname + callback.__name__
  352. except AttributeError:
  353. pass
  354. self._tk.createcommand(cbname, f)
  355. if self._tclCommands is None:
  356. self._tclCommands = []
  357. self._tclCommands.append(cbname)
  358. return cbname
  359. def trace_add(self, mode, callback):
  360. """Define a trace callback for the variable.
  361. Mode is one of "read", "write", "unset", or a list or tuple of
  362. such strings.
  363. Callback must be a function which is called when the variable is
  364. read, written or unset.
  365. Return the name of the callback.
  366. """
  367. cbname = self._register(callback)
  368. self._tk.call('trace', 'add', 'variable',
  369. self._name, mode, (cbname,))
  370. return cbname
  371. def trace_remove(self, mode, cbname):
  372. """Delete the trace callback for a variable.
  373. Mode is one of "read", "write", "unset" or a list or tuple of
  374. such strings. Must be same as were specified in trace_add().
  375. cbname is the name of the callback returned from trace_add().
  376. """
  377. self._tk.call('trace', 'remove', 'variable',
  378. self._name, mode, cbname)
  379. for m, ca in self.trace_info():
  380. if self._tk.splitlist(ca)[0] == cbname:
  381. break
  382. else:
  383. self._tk.deletecommand(cbname)
  384. try:
  385. self._tclCommands.remove(cbname)
  386. except ValueError:
  387. pass
  388. def trace_info(self):
  389. """Return all trace callback information."""
  390. splitlist = self._tk.splitlist
  391. return [(splitlist(k), v) for k, v in map(splitlist,
  392. splitlist(self._tk.call('trace', 'info', 'variable', self._name)))]
  393. def trace_variable(self, mode, callback):
  394. """Define a trace callback for the variable.
  395. MODE is one of "r", "w", "u" for read, write, undefine.
  396. CALLBACK must be a function which is called when
  397. the variable is read, written or undefined.
  398. Return the name of the callback.
  399. This deprecated method wraps a deprecated Tcl method that will
  400. likely be removed in the future. Use trace_add() instead.
  401. """
  402. # TODO: Add deprecation warning
  403. cbname = self._register(callback)
  404. self._tk.call("trace", "variable", self._name, mode, cbname)
  405. return cbname
  406. trace = trace_variable
  407. def trace_vdelete(self, mode, cbname):
  408. """Delete the trace callback for a variable.
  409. MODE is one of "r", "w", "u" for read, write, undefine.
  410. CBNAME is the name of the callback returned from trace_variable or trace.
  411. This deprecated method wraps a deprecated Tcl method that will
  412. likely be removed in the future. Use trace_remove() instead.
  413. """
  414. # TODO: Add deprecation warning
  415. self._tk.call("trace", "vdelete", self._name, mode, cbname)
  416. cbname = self._tk.splitlist(cbname)[0]
  417. for m, ca in self.trace_info():
  418. if self._tk.splitlist(ca)[0] == cbname:
  419. break
  420. else:
  421. self._tk.deletecommand(cbname)
  422. try:
  423. self._tclCommands.remove(cbname)
  424. except ValueError:
  425. pass
  426. def trace_vinfo(self):
  427. """Return all trace callback information.
  428. This deprecated method wraps a deprecated Tcl method that will
  429. likely be removed in the future. Use trace_info() instead.
  430. """
  431. # TODO: Add deprecation warning
  432. return [self._tk.splitlist(x) for x in self._tk.splitlist(
  433. self._tk.call("trace", "vinfo", self._name))]
  434. def __eq__(self, other):
  435. if not isinstance(other, Variable):
  436. return NotImplemented
  437. return (self._name == other._name
  438. and self.__class__.__name__ == other.__class__.__name__
  439. and self._tk == other._tk)
  440. class StringVar(Variable):
  441. """Value holder for strings variables."""
  442. _default = ""
  443. def __init__(self, master=None, value=None, name=None):
  444. """Construct a string variable.
  445. MASTER can be given as master widget.
  446. VALUE is an optional value (defaults to "")
  447. NAME is an optional Tcl name (defaults to PY_VARnum).
  448. If NAME matches an existing variable and VALUE is omitted
  449. then the existing value is retained.
  450. """
  451. Variable.__init__(self, master, value, name)
  452. def get(self):
  453. """Return value of variable as string."""
  454. value = self._tk.globalgetvar(self._name)
  455. if isinstance(value, str):
  456. return value
  457. return str(value)
  458. class IntVar(Variable):
  459. """Value holder for integer variables."""
  460. _default = 0
  461. def __init__(self, master=None, value=None, name=None):
  462. """Construct an integer variable.
  463. MASTER can be given as master widget.
  464. VALUE is an optional value (defaults to 0)
  465. NAME is an optional Tcl name (defaults to PY_VARnum).
  466. If NAME matches an existing variable and VALUE is omitted
  467. then the existing value is retained.
  468. """
  469. Variable.__init__(self, master, value, name)
  470. def get(self):
  471. """Return the value of the variable as an integer."""
  472. value = self._tk.globalgetvar(self._name)
  473. try:
  474. return self._tk.getint(value)
  475. except (TypeError, TclError):
  476. return int(self._tk.getdouble(value))
  477. class DoubleVar(Variable):
  478. """Value holder for float variables."""
  479. _default = 0.0
  480. def __init__(self, master=None, value=None, name=None):
  481. """Construct a float variable.
  482. MASTER can be given as master widget.
  483. VALUE is an optional value (defaults to 0.0)
  484. NAME is an optional Tcl name (defaults to PY_VARnum).
  485. If NAME matches an existing variable and VALUE is omitted
  486. then the existing value is retained.
  487. """
  488. Variable.__init__(self, master, value, name)
  489. def get(self):
  490. """Return the value of the variable as a float."""
  491. return self._tk.getdouble(self._tk.globalgetvar(self._name))
  492. class BooleanVar(Variable):
  493. """Value holder for boolean variables."""
  494. _default = False
  495. def __init__(self, master=None, value=None, name=None):
  496. """Construct a boolean variable.
  497. MASTER can be given as master widget.
  498. VALUE is an optional value (defaults to False)
  499. NAME is an optional Tcl name (defaults to PY_VARnum).
  500. If NAME matches an existing variable and VALUE is omitted
  501. then the existing value is retained.
  502. """
  503. Variable.__init__(self, master, value, name)
  504. def set(self, value):
  505. """Set the variable to VALUE."""
  506. return self._tk.globalsetvar(self._name, self._tk.getboolean(value))
  507. initialize = set
  508. def get(self):
  509. """Return the value of the variable as a bool."""
  510. try:
  511. return self._tk.getboolean(self._tk.globalgetvar(self._name))
  512. except TclError:
  513. raise ValueError("invalid literal for getboolean()")
  514. def mainloop(n=0):
  515. """Run the main loop of Tcl."""
  516. _get_default_root('run the main loop').tk.mainloop(n)
  517. getint = int
  518. getdouble = float
  519. def getboolean(s):
  520. """Convert Tcl object to True or False."""
  521. try:
  522. return _get_default_root('use getboolean()').tk.getboolean(s)
  523. except TclError:
  524. raise ValueError("invalid literal for getboolean()")
  525. # Methods defined on both toplevel and interior widgets
  526. class Misc:
  527. """Internal class.
  528. Base class which defines methods common for interior widgets."""
  529. # used for generating child widget names
  530. _last_child_ids = None
  531. # XXX font command?
  532. _tclCommands = None
  533. def destroy(self):
  534. """Internal function.
  535. Delete all Tcl commands created for
  536. this widget in the Tcl interpreter."""
  537. if self._tclCommands is not None:
  538. for name in self._tclCommands:
  539. #print '- Tkinter: deleted command', name
  540. self.tk.deletecommand(name)
  541. self._tclCommands = None
  542. def deletecommand(self, name):
  543. """Internal function.
  544. Delete the Tcl command provided in NAME."""
  545. #print '- Tkinter: deleted command', name
  546. self.tk.deletecommand(name)
  547. try:
  548. self._tclCommands.remove(name)
  549. except ValueError:
  550. pass
  551. def tk_strictMotif(self, boolean=None):
  552. """Set Tcl internal variable, whether the look and feel
  553. should adhere to Motif.
  554. A parameter of 1 means adhere to Motif (e.g. no color
  555. change if mouse passes over slider).
  556. Returns the set value."""
  557. return self.tk.getboolean(self.tk.call(
  558. 'set', 'tk_strictMotif', boolean))
  559. def tk_bisque(self):
  560. """Change the color scheme to light brown as used in Tk 3.6 and before."""
  561. self.tk.call('tk_bisque')
  562. def tk_setPalette(self, *args, **kw):
  563. """Set a new color scheme for all widget elements.
  564. A single color as argument will cause that all colors of Tk
  565. widget elements are derived from this.
  566. Alternatively several keyword parameters and its associated
  567. colors can be given. The following keywords are valid:
  568. activeBackground, foreground, selectColor,
  569. activeForeground, highlightBackground, selectBackground,
  570. background, highlightColor, selectForeground,
  571. disabledForeground, insertBackground, troughColor."""
  572. self.tk.call(('tk_setPalette',)
  573. + _flatten(args) + _flatten(list(kw.items())))
  574. def wait_variable(self, name='PY_VAR'):
  575. """Wait until the variable is modified.
  576. A parameter of type IntVar, StringVar, DoubleVar or
  577. BooleanVar must be given."""
  578. self.tk.call('tkwait', 'variable', name)
  579. waitvar = wait_variable # XXX b/w compat
  580. def wait_window(self, window=None):
  581. """Wait until a WIDGET is destroyed.
  582. If no parameter is given self is used."""
  583. if window is None:
  584. window = self
  585. self.tk.call('tkwait', 'window', window._w)
  586. def wait_visibility(self, window=None):
  587. """Wait until the visibility of a WIDGET changes
  588. (e.g. it appears).
  589. If no parameter is given self is used."""
  590. if window is None:
  591. window = self
  592. self.tk.call('tkwait', 'visibility', window._w)
  593. def setvar(self, name='PY_VAR', value='1'):
  594. """Set Tcl variable NAME to VALUE."""
  595. self.tk.setvar(name, value)
  596. def getvar(self, name='PY_VAR'):
  597. """Return value of Tcl variable NAME."""
  598. return self.tk.getvar(name)
  599. def getint(self, s):
  600. try:
  601. return self.tk.getint(s)
  602. except TclError as exc:
  603. raise ValueError(str(exc))
  604. def getdouble(self, s):
  605. try:
  606. return self.tk.getdouble(s)
  607. except TclError as exc:
  608. raise ValueError(str(exc))
  609. def getboolean(self, s):
  610. """Return a boolean value for Tcl boolean values true and false given as parameter."""
  611. try:
  612. return self.tk.getboolean(s)
  613. except TclError:
  614. raise ValueError("invalid literal for getboolean()")
  615. def focus_set(self):
  616. """Direct input focus to this widget.
  617. If the application currently does not have the focus
  618. this widget will get the focus if the application gets
  619. the focus through the window manager."""
  620. self.tk.call('focus', self._w)
  621. focus = focus_set # XXX b/w compat?
  622. def focus_force(self):
  623. """Direct input focus to this widget even if the
  624. application does not have the focus. Use with
  625. caution!"""
  626. self.tk.call('focus', '-force', self._w)
  627. def focus_get(self):
  628. """Return the widget which has currently the focus in the
  629. application.
  630. Use focus_displayof to allow working with several
  631. displays. Return None if application does not have
  632. the focus."""
  633. name = self.tk.call('focus')
  634. if name == 'none' or not name: return None
  635. return self._nametowidget(name)
  636. def focus_displayof(self):
  637. """Return the widget which has currently the focus on the
  638. display where this widget is located.
  639. Return None if the application does not have the focus."""
  640. name = self.tk.call('focus', '-displayof', self._w)
  641. if name == 'none' or not name: return None
  642. return self._nametowidget(name)
  643. def focus_lastfor(self):
  644. """Return the widget which would have the focus if top level
  645. for this widget gets the focus from the window manager."""
  646. name = self.tk.call('focus', '-lastfor', self._w)
  647. if name == 'none' or not name: return None
  648. return self._nametowidget(name)
  649. def tk_focusFollowsMouse(self):
  650. """The widget under mouse will get automatically focus. Can not
  651. be disabled easily."""
  652. self.tk.call('tk_focusFollowsMouse')
  653. def tk_focusNext(self):
  654. """Return the next widget in the focus order which follows
  655. widget which has currently the focus.
  656. The focus order first goes to the next child, then to
  657. the children of the child recursively and then to the
  658. next sibling which is higher in the stacking order. A
  659. widget is omitted if it has the takefocus resource set
  660. to 0."""
  661. name = self.tk.call('tk_focusNext', self._w)
  662. if not name: return None
  663. return self._nametowidget(name)
  664. def tk_focusPrev(self):
  665. """Return previous widget in the focus order. See tk_focusNext for details."""
  666. name = self.tk.call('tk_focusPrev', self._w)
  667. if not name: return None
  668. return self._nametowidget(name)
  669. def after(self, ms, func=None, *args):
  670. """Call function once after given time.
  671. MS specifies the time in milliseconds. FUNC gives the
  672. function which shall be called. Additional parameters
  673. are given as parameters to the function call. Return
  674. identifier to cancel scheduling with after_cancel."""
  675. if func is None:
  676. # I'd rather use time.sleep(ms*0.001)
  677. self.tk.call('after', ms)
  678. return None
  679. else:
  680. def callit():
  681. try:
  682. func(*args)
  683. finally:
  684. try:
  685. self.deletecommand(name)
  686. except TclError:
  687. pass
  688. try:
  689. callit.__name__ = func.__name__
  690. except AttributeError:
  691. # Required for callable classes (bpo-44404)
  692. callit.__name__ = type(func).__name__
  693. name = self._register(callit)
  694. return self.tk.call('after', ms, name)
  695. def after_idle(self, func, *args):
  696. """Call FUNC once if the Tcl main loop has no event to
  697. process.
  698. Return an identifier to cancel the scheduling with
  699. after_cancel."""
  700. return self.after('idle', func, *args)
  701. def after_cancel(self, id):
  702. """Cancel scheduling of function identified with ID.
  703. Identifier returned by after or after_idle must be
  704. given as first parameter.
  705. """
  706. if not id:
  707. raise ValueError('id must be a valid identifier returned from '
  708. 'after or after_idle')
  709. try:
  710. data = self.tk.call('after', 'info', id)
  711. script = self.tk.splitlist(data)[0]
  712. self.deletecommand(script)
  713. except TclError:
  714. pass
  715. self.tk.call('after', 'cancel', id)
  716. def bell(self, displayof=0):
  717. """Ring a display's bell."""
  718. self.tk.call(('bell',) + self._displayof(displayof))
  719. # Clipboard handling:
  720. def clipboard_get(self, **kw):
  721. """Retrieve data from the clipboard on window's display.
  722. The window keyword defaults to the root window of the Tkinter
  723. application.
  724. The type keyword specifies the form in which the data is
  725. to be returned and should be an atom name such as STRING
  726. or FILE_NAME. Type defaults to STRING, except on X11, where the default
  727. is to try UTF8_STRING and fall back to STRING.
  728. This command is equivalent to:
  729. selection_get(CLIPBOARD)
  730. """
  731. if 'type' not in kw and self._windowingsystem == 'x11':
  732. try:
  733. kw['type'] = 'UTF8_STRING'
  734. return self.tk.call(('clipboard', 'get') + self._options(kw))
  735. except TclError:
  736. del kw['type']
  737. return self.tk.call(('clipboard', 'get') + self._options(kw))
  738. def clipboard_clear(self, **kw):
  739. """Clear the data in the Tk clipboard.
  740. A widget specified for the optional displayof keyword
  741. argument specifies the target display."""
  742. if 'displayof' not in kw: kw['displayof'] = self._w
  743. self.tk.call(('clipboard', 'clear') + self._options(kw))
  744. def clipboard_append(self, string, **kw):
  745. """Append STRING to the Tk clipboard.
  746. A widget specified at the optional displayof keyword
  747. argument specifies the target display. The clipboard
  748. can be retrieved with selection_get."""
  749. if 'displayof' not in kw: kw['displayof'] = self._w
  750. self.tk.call(('clipboard', 'append') + self._options(kw)
  751. + ('--', string))
  752. # XXX grab current w/o window argument
  753. def grab_current(self):
  754. """Return widget which has currently the grab in this application
  755. or None."""
  756. name = self.tk.call('grab', 'current', self._w)
  757. if not name: return None
  758. return self._nametowidget(name)
  759. def grab_release(self):
  760. """Release grab for this widget if currently set."""
  761. self.tk.call('grab', 'release', self._w)
  762. def grab_set(self):
  763. """Set grab for this widget.
  764. A grab directs all events to this and descendant
  765. widgets in the application."""
  766. self.tk.call('grab', 'set', self._w)
  767. def grab_set_global(self):
  768. """Set global grab for this widget.
  769. A global grab directs all events to this and
  770. descendant widgets on the display. Use with caution -
  771. other applications do not get events anymore."""
  772. self.tk.call('grab', 'set', '-global', self._w)
  773. def grab_status(self):
  774. """Return None, "local" or "global" if this widget has
  775. no, a local or a global grab."""
  776. status = self.tk.call('grab', 'status', self._w)
  777. if status == 'none': status = None
  778. return status
  779. def option_add(self, pattern, value, priority = None):
  780. """Set a VALUE (second parameter) for an option
  781. PATTERN (first parameter).
  782. An optional third parameter gives the numeric priority
  783. (defaults to 80)."""
  784. self.tk.call('option', 'add', pattern, value, priority)
  785. def option_clear(self):
  786. """Clear the option database.
  787. It will be reloaded if option_add is called."""
  788. self.tk.call('option', 'clear')
  789. def option_get(self, name, className):
  790. """Return the value for an option NAME for this widget
  791. with CLASSNAME.
  792. Values with higher priority override lower values."""
  793. return self.tk.call('option', 'get', self._w, name, className)
  794. def option_readfile(self, fileName, priority = None):
  795. """Read file FILENAME into the option database.
  796. An optional second parameter gives the numeric
  797. priority."""
  798. self.tk.call('option', 'readfile', fileName, priority)
  799. def selection_clear(self, **kw):
  800. """Clear the current X selection."""
  801. if 'displayof' not in kw: kw['displayof'] = self._w
  802. self.tk.call(('selection', 'clear') + self._options(kw))
  803. def selection_get(self, **kw):
  804. """Return the contents of the current X selection.
  805. A keyword parameter selection specifies the name of
  806. the selection and defaults to PRIMARY. A keyword
  807. parameter displayof specifies a widget on the display
  808. to use. A keyword parameter type specifies the form of data to be
  809. fetched, defaulting to STRING except on X11, where UTF8_STRING is tried
  810. before STRING."""
  811. if 'displayof' not in kw: kw['displayof'] = self._w
  812. if 'type' not in kw and self._windowingsystem == 'x11':
  813. try:
  814. kw['type'] = 'UTF8_STRING'
  815. return self.tk.call(('selection', 'get') + self._options(kw))
  816. except TclError:
  817. del kw['type']
  818. return self.tk.call(('selection', 'get') + self._options(kw))
  819. def selection_handle(self, command, **kw):
  820. """Specify a function COMMAND to call if the X
  821. selection owned by this widget is queried by another
  822. application.
  823. This function must return the contents of the
  824. selection. The function will be called with the
  825. arguments OFFSET and LENGTH which allows the chunking
  826. of very long selections. The following keyword
  827. parameters can be provided:
  828. selection - name of the selection (default PRIMARY),
  829. type - type of the selection (e.g. STRING, FILE_NAME)."""
  830. name = self._register(command)
  831. self.tk.call(('selection', 'handle') + self._options(kw)
  832. + (self._w, name))
  833. def selection_own(self, **kw):
  834. """Become owner of X selection.
  835. A keyword parameter selection specifies the name of
  836. the selection (default PRIMARY)."""
  837. self.tk.call(('selection', 'own') +
  838. self._options(kw) + (self._w,))
  839. def selection_own_get(self, **kw):
  840. """Return owner of X selection.
  841. The following keyword parameter can
  842. be provided:
  843. selection - name of the selection (default PRIMARY),
  844. type - type of the selection (e.g. STRING, FILE_NAME)."""
  845. if 'displayof' not in kw: kw['displayof'] = self._w
  846. name = self.tk.call(('selection', 'own') + self._options(kw))
  847. if not name: return None
  848. return self._nametowidget(name)
  849. def send(self, interp, cmd, *args):
  850. """Send Tcl command CMD to different interpreter INTERP to be executed."""
  851. return self.tk.call(('send', interp, cmd) + args)
  852. def lower(self, belowThis=None):
  853. """Lower this widget in the stacking order."""
  854. self.tk.call('lower', self._w, belowThis)
  855. def tkraise(self, aboveThis=None):
  856. """Raise this widget in the stacking order."""
  857. self.tk.call('raise', self._w, aboveThis)
  858. lift = tkraise
  859. def winfo_atom(self, name, displayof=0):
  860. """Return integer which represents atom NAME."""
  861. args = ('winfo', 'atom') + self._displayof(displayof) + (name,)
  862. return self.tk.getint(self.tk.call(args))
  863. def winfo_atomname(self, id, displayof=0):
  864. """Return name of atom with identifier ID."""
  865. args = ('winfo', 'atomname') \
  866. + self._displayof(displayof) + (id,)
  867. return self.tk.call(args)
  868. def winfo_cells(self):
  869. """Return number of cells in the colormap for this widget."""
  870. return self.tk.getint(
  871. self.tk.call('winfo', 'cells', self._w))
  872. def winfo_children(self):
  873. """Return a list of all widgets which are children of this widget."""
  874. result = []
  875. for child in self.tk.splitlist(
  876. self.tk.call('winfo', 'children', self._w)):
  877. try:
  878. # Tcl sometimes returns extra windows, e.g. for
  879. # menus; those need to be skipped
  880. result.append(self._nametowidget(child))
  881. except KeyError:
  882. pass
  883. return result
  884. def winfo_class(self):
  885. """Return window class name of this widget."""
  886. return self.tk.call('winfo', 'class', self._w)
  887. def winfo_colormapfull(self):
  888. """Return True if at the last color request the colormap was full."""
  889. return self.tk.getboolean(
  890. self.tk.call('winfo', 'colormapfull', self._w))
  891. def winfo_containing(self, rootX, rootY, displayof=0):
  892. """Return the widget which is at the root coordinates ROOTX, ROOTY."""
  893. args = ('winfo', 'containing') \
  894. + self._displayof(displayof) + (rootX, rootY)
  895. name = self.tk.call(args)
  896. if not name: return None
  897. return self._nametowidget(name)
  898. def winfo_depth(self):
  899. """Return the number of bits per pixel."""
  900. return self.tk.getint(self.tk.call('winfo', 'depth', self._w))
  901. def winfo_exists(self):
  902. """Return true if this widget exists."""
  903. return self.tk.getint(
  904. self.tk.call('winfo', 'exists', self._w))
  905. def winfo_fpixels(self, number):
  906. """Return the number of pixels for the given distance NUMBER
  907. (e.g. "3c") as float."""
  908. return self.tk.getdouble(self.tk.call(
  909. 'winfo', 'fpixels', self._w, number))
  910. def winfo_geometry(self):
  911. """Return geometry string for this widget in the form "widthxheight+X+Y"."""
  912. return self.tk.call('winfo', 'geometry', self._w)
  913. def winfo_height(self):
  914. """Return height of this widget."""
  915. return self.tk.getint(
  916. self.tk.call('winfo', 'height', self._w))
  917. def winfo_id(self):
  918. """Return identifier ID for this widget."""
  919. return int(self.tk.call('winfo', 'id', self._w), 0)
  920. def winfo_interps(self, displayof=0):
  921. """Return the name of all Tcl interpreters for this display."""
  922. args = ('winfo', 'interps') + self._displayof(displayof)
  923. return self.tk.splitlist(self.tk.call(args))
  924. def winfo_ismapped(self):
  925. """Return true if this widget is mapped."""
  926. return self.tk.getint(
  927. self.tk.call('winfo', 'ismapped', self._w))
  928. def winfo_manager(self):
  929. """Return the window manager name for this widget."""
  930. return self.tk.call('winfo', 'manager', self._w)
  931. def winfo_name(self):
  932. """Return the name of this widget."""
  933. return self.tk.call('winfo', 'name', self._w)
  934. def winfo_parent(self):
  935. """Return the name of the parent of this widget."""
  936. return self.tk.call('winfo', 'parent', self._w)
  937. def winfo_pathname(self, id, displayof=0):
  938. """Return the pathname of the widget given by ID."""
  939. args = ('winfo', 'pathname') \
  940. + self._displayof(displayof) + (id,)
  941. return self.tk.call(args)
  942. def winfo_pixels(self, number):
  943. """Rounded integer value of winfo_fpixels."""
  944. return self.tk.getint(
  945. self.tk.call('winfo', 'pixels', self._w, number))
  946. def winfo_pointerx(self):
  947. """Return the x coordinate of the pointer on the root window."""
  948. return self.tk.getint(
  949. self.tk.call('winfo', 'pointerx', self._w))
  950. def winfo_pointerxy(self):
  951. """Return a tuple of x and y coordinates of the pointer on the root window."""
  952. return self._getints(
  953. self.tk.call('winfo', 'pointerxy', self._w))
  954. def winfo_pointery(self):
  955. """Return the y coordinate of the pointer on the root window."""
  956. return self.tk.getint(
  957. self.tk.call('winfo', 'pointery', self._w))
  958. def winfo_reqheight(self):
  959. """Return requested height of this widget."""
  960. return self.tk.getint(
  961. self.tk.call('winfo', 'reqheight', self._w))
  962. def winfo_reqwidth(self):
  963. """Return requested width of this widget."""
  964. return self.tk.getint(
  965. self.tk.call('winfo', 'reqwidth', self._w))
  966. def winfo_rgb(self, color):
  967. """Return a tuple of integer RGB values in range(65536) for color in this widget."""
  968. return self._getints(
  969. self.tk.call('winfo', 'rgb', self._w, color))
  970. def winfo_rootx(self):
  971. """Return x coordinate of upper left corner of this widget on the
  972. root window."""
  973. return self.tk.getint(
  974. self.tk.call('winfo', 'rootx', self._w))
  975. def winfo_rooty(self):
  976. """Return y coordinate of upper left corner of this widget on the
  977. root window."""
  978. return self.tk.getint(
  979. self.tk.call('winfo', 'rooty', self._w))
  980. def winfo_screen(self):
  981. """Return the screen name of this widget."""
  982. return self.tk.call('winfo', 'screen', self._w)
  983. def winfo_screencells(self):
  984. """Return the number of the cells in the colormap of the screen
  985. of this widget."""
  986. return self.tk.getint(
  987. self.tk.call('winfo', 'screencells', self._w))
  988. def winfo_screendepth(self):
  989. """Return the number of bits per pixel of the root window of the
  990. screen of this widget."""
  991. return self.tk.getint(
  992. self.tk.call('winfo', 'screendepth', self._w))
  993. def winfo_screenheight(self):
  994. """Return the number of pixels of the height of the screen of this widget
  995. in pixel."""
  996. return self.tk.getint(
  997. self.tk.call('winfo', 'screenheight', self._w))
  998. def winfo_screenmmheight(self):
  999. """Return the number of pixels of the height of the screen of
  1000. this widget in mm."""
  1001. return self.tk.getint(
  1002. self.tk.call('winfo', 'screenmmheight', self._w))
  1003. def winfo_screenmmwidth(self):
  1004. """Return the number of pixels of the width of the screen of
  1005. this widget in mm."""
  1006. return self.tk.getint(
  1007. self.tk.call('winfo', 'screenmmwidth', self._w))
  1008. def winfo_screenvisual(self):
  1009. """Return one of the strings directcolor, grayscale, pseudocolor,
  1010. staticcolor, staticgray, or truecolor for the default
  1011. colormodel of this screen."""
  1012. return self.tk.call('winfo', 'screenvisual', self._w)
  1013. def winfo_screenwidth(self):
  1014. """Return the number of pixels of the width of the screen of
  1015. this widget in pixel."""
  1016. return self.tk.getint(
  1017. self.tk.call('winfo', 'screenwidth', self._w))
  1018. def winfo_server(self):
  1019. """Return information of the X-Server of the screen of this widget in
  1020. the form "XmajorRminor vendor vendorVersion"."""
  1021. return self.tk.call('winfo', 'server', self._w)
  1022. def winfo_toplevel(self):
  1023. """Return the toplevel widget of this widget."""
  1024. return self._nametowidget(self.tk.call(
  1025. 'winfo', 'toplevel', self._w))
  1026. def winfo_viewable(self):
  1027. """Return true if the widget and all its higher ancestors are mapped."""
  1028. return self.tk.getint(
  1029. self.tk.call('winfo', 'viewable', self._w))
  1030. def winfo_visual(self):
  1031. """Return one of the strings directcolor, grayscale, pseudocolor,
  1032. staticcolor, staticgray, or truecolor for the
  1033. colormodel of this widget."""
  1034. return self.tk.call('winfo', 'visual', self._w)
  1035. def winfo_visualid(self):
  1036. """Return the X identifier for the visual for this widget."""
  1037. return self.tk.call('winfo', 'visualid', self._w)
  1038. def winfo_visualsavailable(self, includeids=False):
  1039. """Return a list of all visuals available for the screen
  1040. of this widget.
  1041. Each item in the list consists of a visual name (see winfo_visual), a
  1042. depth and if includeids is true is given also the X identifier."""
  1043. data = self.tk.call('winfo', 'visualsavailable', self._w,
  1044. 'includeids' if includeids else None)
  1045. data = [self.tk.splitlist(x) for x in self.tk.splitlist(data)]
  1046. return [self.__winfo_parseitem(x) for x in data]
  1047. def __winfo_parseitem(self, t):
  1048. """Internal function."""
  1049. return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
  1050. def __winfo_getint(self, x):
  1051. """Internal function."""
  1052. return int(x, 0)
  1053. def winfo_vrootheight(self):
  1054. """Return the height of the virtual root window associated with this
  1055. widget in pixels. If there is no virtual root window return the
  1056. height of the screen."""
  1057. return self.tk.getint(
  1058. self.tk.call('winfo', 'vrootheight', self._w))
  1059. def winfo_vrootwidth(self):
  1060. """Return the width of the virtual root window associated with this
  1061. widget in pixel. If there is no virtual root window return the
  1062. width of the screen."""
  1063. return self.tk.getint(
  1064. self.tk.call('winfo', 'vrootwidth', self._w))
  1065. def winfo_vrootx(self):
  1066. """Return the x offset of the virtual root relative to the root
  1067. window of the screen of this widget."""
  1068. return self.tk.getint(
  1069. self.tk.call('winfo', 'vrootx', self._w))
  1070. def winfo_vrooty(self):
  1071. """Return the y offset of the virtual root relative to the root
  1072. window of the screen of this widget."""
  1073. return self.tk.getint(
  1074. self.tk.call('winfo', 'vrooty', self._w))
  1075. def winfo_width(self):
  1076. """Return the width of this widget."""
  1077. return self.tk.getint(
  1078. self.tk.call('winfo', 'width', self._w))
  1079. def winfo_x(self):
  1080. """Return the x coordinate of the upper left corner of this widget
  1081. in the parent."""
  1082. return self.tk.getint(
  1083. self.tk.call('winfo', 'x', self._w))
  1084. def winfo_y(self):
  1085. """Return the y coordinate of the upper left corner of this widget
  1086. in the parent."""
  1087. return self.tk.getint(
  1088. self.tk.call('winfo', 'y', self._w))
  1089. def update(self):
  1090. """Enter event loop until all pending events have been processed by Tcl."""
  1091. self.tk.call('update')
  1092. def update_idletasks(self):
  1093. """Enter event loop until all idle callbacks have been called. This
  1094. will update the display of windows but not process events caused by
  1095. the user."""
  1096. self.tk.call('update', 'idletasks')
  1097. def bindtags(self, tagList=None):
  1098. """Set or get the list of bindtags for this widget.
  1099. With no argument return the list of all bindtags associated with
  1100. this widget. With a list of strings as argument the bindtags are
  1101. set to this list. The bindtags determine in which order events are
  1102. processed (see bind)."""
  1103. if tagList is None:
  1104. return self.tk.splitlist(
  1105. self.tk.call('bindtags', self._w))
  1106. else:
  1107. self.tk.call('bindtags', self._w, tagList)
  1108. def _bind(self, what, sequence, func, add, needcleanup=1):
  1109. """Internal function."""
  1110. if isinstance(func, str):
  1111. self.tk.call(what + (sequence, func))
  1112. elif func:
  1113. funcid = self._register(func, self._substitute,
  1114. needcleanup)
  1115. cmd = ('%sif {"[%s %s]" == "break"} break\n'
  1116. %
  1117. (add and '+' or '',
  1118. funcid, self._subst_format_str))
  1119. self.tk.call(what + (sequence, cmd))
  1120. return funcid
  1121. elif sequence:
  1122. return self.tk.call(what + (sequence,))
  1123. else:
  1124. return self.tk.splitlist(self.tk.call(what))
  1125. def bind(self, sequence=None, func=None, add=None):
  1126. """Bind to this widget at event SEQUENCE a call to function FUNC.
  1127. SEQUENCE is a string of concatenated event
  1128. patterns. An event pattern is of the form
  1129. <MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
  1130. of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
  1131. Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
  1132. B3, Alt, Button4, B4, Double, Button5, B5 Triple,
  1133. Mod1, M1. TYPE is one of Activate, Enter, Map,
  1134. ButtonPress, Button, Expose, Motion, ButtonRelease
  1135. FocusIn, MouseWheel, Circulate, FocusOut, Property,
  1136. Colormap, Gravity Reparent, Configure, KeyPress, Key,
  1137. Unmap, Deactivate, KeyRelease Visibility, Destroy,
  1138. Leave and DETAIL is the button number for ButtonPress,
  1139. ButtonRelease and DETAIL is the Keysym for KeyPress and
  1140. KeyRelease. Examples are
  1141. <Control-Button-1> for pressing Control and mouse button 1 or
  1142. <Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
  1143. An event pattern can also be a virtual event of the form
  1144. <<AString>> where AString can be arbitrary. This
  1145. event can be generated by event_generate.
  1146. If events are concatenated they must appear shortly
  1147. after each other.
  1148. FUNC will be called if the event sequence occurs with an
  1149. instance of Event as argument. If the return value of FUNC is
  1150. "break" no further bound function is invoked.
  1151. An additional boolean parameter ADD specifies whether FUNC will
  1152. be called additionally to the other bound function or whether
  1153. it will replace the previous function.
  1154. Bind will return an identifier to allow deletion of the bound function with
  1155. unbind without memory leak.
  1156. If FUNC or SEQUENCE is omitted the bound function or list
  1157. of bound events are returned."""
  1158. return self._bind(('bind', self._w), sequence, func, add)
  1159. def unbind(self, sequence, funcid=None):
  1160. """Unbind for this widget for event SEQUENCE the
  1161. function identified with FUNCID."""
  1162. self.tk.call('bind', self._w, sequence, '')
  1163. if funcid:
  1164. self.deletecommand(funcid)
  1165. def bind_all(self, sequence=None, func=None, add=None):
  1166. """Bind to all widgets at an event SEQUENCE a call to function FUNC.
  1167. An additional boolean parameter ADD specifies whether FUNC will
  1168. be called additionally to the other bound function or whether
  1169. it will replace the previous function. See bind for the return value."""
  1170. return self._bind(('bind', 'all'), sequence, func, add, 0)
  1171. def unbind_all(self, sequence):
  1172. """Unbind for all widgets for event SEQUENCE all functions."""
  1173. self.tk.call('bind', 'all' , sequence, '')
  1174. def bind_class(self, className, sequence=None, func=None, add=None):
  1175. """Bind to widgets with bindtag CLASSNAME at event
  1176. SEQUENCE a call of function FUNC. An additional
  1177. boolean parameter ADD specifies whether FUNC will be
  1178. called additionally to the other bound function or
  1179. whether it will replace the previous function. See bind for
  1180. the return value."""
  1181. return self._bind(('bind', className), sequence, func, add, 0)
  1182. def unbind_class(self, className, sequence):
  1183. """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE
  1184. all functions."""
  1185. self.tk.call('bind', className , sequence, '')
  1186. def mainloop(self, n=0):
  1187. """Call the mainloop of Tk."""
  1188. self.tk.mainloop(n)
  1189. def quit(self):
  1190. """Quit the Tcl interpreter. All widgets will be destroyed."""
  1191. self.tk.quit()
  1192. def _getints(self, string):
  1193. """Internal function."""
  1194. if string:
  1195. return tuple(map(self.tk.getint, self.tk.splitlist(string)))
  1196. def _getdoubles(self, string):
  1197. """Internal function."""
  1198. if string:
  1199. return tuple(map(self.tk.getdouble, self.tk.splitlist(string)))
  1200. def _getboolean(self, string):
  1201. """Internal function."""
  1202. if string:
  1203. return self.tk.getboolean(string)
  1204. def _displayof(self, displayof):
  1205. """Internal function."""
  1206. if displayof:
  1207. return ('-displayof', displayof)
  1208. if displayof is None:
  1209. return ('-displayof', self._w)
  1210. return ()
  1211. @property
  1212. def _windowingsystem(self):
  1213. """Internal function."""
  1214. try:
  1215. return self._root()._windowingsystem_cached
  1216. except AttributeError:
  1217. ws = self._root()._windowingsystem_cached = \
  1218. self.tk.call('tk', 'windowingsystem')
  1219. return ws
  1220. def _options(self, cnf, kw = None):
  1221. """Internal function."""
  1222. if kw:
  1223. cnf = _cnfmerge((cnf, kw))
  1224. else:
  1225. cnf = _cnfmerge(cnf)
  1226. res = ()
  1227. for k, v in cnf.items():
  1228. if v is not None:
  1229. if k[-1] == '_': k = k[:-1]
  1230. if callable(v):
  1231. v = self._register(v)
  1232. elif isinstance(v, (tuple, list)):
  1233. nv = []
  1234. for item in v:
  1235. if isinstance(item, int):
  1236. nv.append(str(item))
  1237. elif isinstance(item, str):
  1238. nv.append(_stringify(item))
  1239. else:
  1240. break
  1241. else:
  1242. v = ' '.join(nv)
  1243. res = res + ('-'+k, v)
  1244. return res
  1245. def nametowidget(self, name):
  1246. """Return the Tkinter instance of a widget identified by
  1247. its Tcl name NAME."""
  1248. name = str(name).split('.')
  1249. w = self
  1250. if not name[0]:
  1251. w = w._root()
  1252. name = name[1:]
  1253. for n in name:
  1254. if not n:
  1255. break
  1256. w = w.children[n]
  1257. return w
  1258. _nametowidget = nametowidget
  1259. def _register(self, func, subst=None, needcleanup=1):
  1260. """Return a newly created Tcl function. If this
  1261. function is called, the Python function FUNC will
  1262. be executed. An optional function SUBST can
  1263. be given which will be executed before FUNC."""
  1264. f = CallWrapper(func, subst, self).__call__
  1265. name = repr(id(f))
  1266. try:
  1267. func = func.__func__
  1268. except AttributeError:
  1269. pass
  1270. try:
  1271. name = name + func.__name__
  1272. except AttributeError:
  1273. pass
  1274. self.tk.createcommand(name, f)
  1275. if needcleanup:
  1276. if self._tclCommands is None:
  1277. self._tclCommands = []
  1278. self._tclCommands.append(name)
  1279. return name
  1280. register = _register
  1281. def _root(self):
  1282. """Internal function."""
  1283. w = self
  1284. while w.master is not None: w = w.master
  1285. return w
  1286. _subst_format = ('%#', '%b', '%f', '%h', '%k',
  1287. '%s', '%t', '%w', '%x', '%y',
  1288. '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D')
  1289. _subst_format_str = " ".join(_subst_format)
  1290. def _substitute(self, *args):
  1291. """Internal function."""
  1292. if len(args) != len(self._subst_format): return args
  1293. getboolean = self.tk.getboolean
  1294. getint = self.tk.getint
  1295. def getint_event(s):
  1296. """Tk changed behavior in 8.4.2, returning "??" rather more often."""
  1297. try:
  1298. return getint(s)
  1299. except (ValueError, TclError):
  1300. return s
  1301. nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args
  1302. # Missing: (a, c, d, m, o, v, B, R)
  1303. e = Event()
  1304. # serial field: valid for all events
  1305. # number of button: ButtonPress and ButtonRelease events only
  1306. # height field: Configure, ConfigureRequest, Create,
  1307. # ResizeRequest, and Expose events only
  1308. # keycode field: KeyPress and KeyRelease events only
  1309. # time field: "valid for events that contain a time field"
  1310. # width field: Configure, ConfigureRequest, Create, ResizeRequest,
  1311. # and Expose events only
  1312. # x field: "valid for events that contain an x field"
  1313. # y field: "valid for events that contain a y field"
  1314. # keysym as decimal: KeyPress and KeyRelease events only
  1315. # x_root, y_root fields: ButtonPress, ButtonRelease, KeyPress,
  1316. # KeyRelease, and Motion events
  1317. e.serial = getint(nsign)
  1318. e.num = getint_event(b)
  1319. try: e.focus = getboolean(f)
  1320. except TclError: pass
  1321. e.height = getint_event(h)
  1322. e.keycode = getint_event(k)
  1323. e.state = getint_event(s)
  1324. e.time = getint_event(t)
  1325. e.width = getint_event(w)
  1326. e.x = getint_event(x)
  1327. e.y = getint_event(y)
  1328. e.char = A
  1329. try: e.send_event = getboolean(E)
  1330. except TclError: pass
  1331. e.keysym = K
  1332. e.keysym_num = getint_event(N)
  1333. try:
  1334. e.type = EventType(T)
  1335. except ValueError:
  1336. e.type = T
  1337. try:
  1338. e.widget = self._nametowidget(W)
  1339. except KeyError:
  1340. e.widget = W
  1341. e.x_root = getint_event(X)
  1342. e.y_root = getint_event(Y)
  1343. try:
  1344. e.delta = getint(D)
  1345. except (ValueError, TclError):
  1346. e.delta = 0
  1347. return (e,)
  1348. def _report_exception(self):
  1349. """Internal function."""
  1350. exc, val, tb = sys.exc_info()
  1351. root = self._root()
  1352. root.report_callback_exception(exc, val, tb)
  1353. def _getconfigure(self, *args):
  1354. """Call Tcl configure command and return the result as a dict."""
  1355. cnf = {}
  1356. for x in self.tk.splitlist(self.tk.call(*args)):
  1357. x = self.tk.splitlist(x)
  1358. cnf[x[0][1:]] = (x[0][1:],) + x[1:]
  1359. return cnf
  1360. def _getconfigure1(self, *args):
  1361. x = self.tk.splitlist(self.tk.call(*args))
  1362. return (x[0][1:],) + x[1:]
  1363. def _configure(self, cmd, cnf, kw):
  1364. """Internal function."""
  1365. if kw:
  1366. cnf = _cnfmerge((cnf, kw))
  1367. elif cnf:
  1368. cnf = _cnfmerge(cnf)
  1369. if cnf is None:
  1370. return self._getconfigure(_flatten((self._w, cmd)))
  1371. if isinstance(cnf, str):
  1372. return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
  1373. self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
  1374. # These used to be defined in Widget:
  1375. def configure(self, cnf=None, **kw):
  1376. """Configure resources of a widget.
  1377. The values for resources are specified as keyword
  1378. arguments. To get an overview about
  1379. the allowed keyword arguments call the method keys.
  1380. """
  1381. return self._configure('configure', cnf, kw)
  1382. config = configure
  1383. def cget(self, key):
  1384. """Return the resource value for a KEY given as string."""
  1385. return self.tk.call(self._w, 'cget', '-' + key)
  1386. __getitem__ = cget
  1387. def __setitem__(self, key, value):
  1388. self.configure({key: value})
  1389. def keys(self):
  1390. """Return a list of all resource names of this widget."""
  1391. splitlist = self.tk.splitlist
  1392. return [splitlist(x)[0][1:] for x in
  1393. splitlist(self.tk.call(self._w, 'configure'))]
  1394. def __str__(self):
  1395. """Return the window path name of this widget."""
  1396. return self._w
  1397. def __repr__(self):
  1398. return '<%s.%s object %s>' % (
  1399. self.__class__.__module__, self.__class__.__qualname__, self._w)
  1400. # Pack methods that apply to the master
  1401. _noarg_ = ['_noarg_']
  1402. def pack_propagate(self, flag=_noarg_):
  1403. """Set or get the status for propagation of geometry information.
  1404. A boolean argument specifies whether the geometry information
  1405. of the slaves will determine the size of this widget. If no argument
  1406. is given the current setting will be returned.
  1407. """
  1408. if flag is Misc._noarg_:
  1409. return self._getboolean(self.tk.call(
  1410. 'pack', 'propagate', self._w))
  1411. else:
  1412. self.tk.call('pack', 'propagate', self._w, flag)
  1413. propagate = pack_propagate
  1414. def pack_slaves(self):
  1415. """Return a list of all slaves of this widget
  1416. in its packing order."""
  1417. return [self._nametowidget(x) for x in
  1418. self.tk.splitlist(
  1419. self.tk.call('pack', 'slaves', self._w))]
  1420. slaves = pack_slaves
  1421. # Place method that applies to the master
  1422. def place_slaves(self):
  1423. """Return a list of all slaves of this widget
  1424. in its packing order."""
  1425. return [self._nametowidget(x) for x in
  1426. self.tk.splitlist(
  1427. self.tk.call(
  1428. 'place', 'slaves', self._w))]
  1429. # Grid methods that apply to the master
  1430. def grid_anchor(self, anchor=None): # new in Tk 8.5
  1431. """The anchor value controls how to place the grid within the
  1432. master when no row/column has any weight.
  1433. The default anchor is nw."""
  1434. self.tk.call('grid', 'anchor', self._w, anchor)
  1435. anchor = grid_anchor
  1436. def grid_bbox(self, column=None, row=None, col2=None, row2=None):
  1437. """Return a tuple of integer coordinates for the bounding
  1438. box of this widget controlled by the geometry manager grid.
  1439. If COLUMN, ROW is given the bounding box applies from
  1440. the cell with row and column 0 to the specified
  1441. cell. If COL2 and ROW2 are given the bounding box
  1442. starts at that cell.
  1443. The returned integers specify the offset of the upper left
  1444. corner in the master widget and the width and height.
  1445. """
  1446. args = ('grid', 'bbox', self._w)
  1447. if column is not None and row is not None:
  1448. args = args + (column, row)
  1449. if col2 is not None and row2 is not None:
  1450. args = args + (col2, row2)
  1451. return self._getints(self.tk.call(*args)) or None
  1452. bbox = grid_bbox
  1453. def _gridconvvalue(self, value):
  1454. if isinstance(value, (str, _tkinter.Tcl_Obj)):
  1455. try:
  1456. svalue = str(value)
  1457. if not svalue:
  1458. return None
  1459. elif '.' in svalue:
  1460. return self.tk.getdouble(svalue)
  1461. else:
  1462. return self.tk.getint(svalue)
  1463. except (ValueError, TclError):
  1464. pass
  1465. return value
  1466. def _grid_configure(self, command, index, cnf, kw):
  1467. """Internal function."""
  1468. if isinstance(cnf, str) and not kw:
  1469. if cnf[-1:] == '_':
  1470. cnf = cnf[:-1]
  1471. if cnf[:1] != '-':
  1472. cnf = '-'+cnf
  1473. options = (cnf,)
  1474. else:
  1475. options = self._options(cnf, kw)
  1476. if not options:
  1477. return _splitdict(
  1478. self.tk,
  1479. self.tk.call('grid', command, self._w, index),
  1480. conv=self._gridconvvalue)
  1481. res = self.tk.call(
  1482. ('grid', command, self._w, index)
  1483. + options)
  1484. if len(options) == 1:
  1485. return self._gridconvvalue(res)
  1486. def grid_columnconfigure(self, index, cnf={}, **kw):
  1487. """Configure column INDEX of a grid.
  1488. Valid resources are minsize (minimum size of the column),
  1489. weight (how much does additional space propagate to this column)
  1490. and pad (how much space to let additionally)."""
  1491. return self._grid_configure('columnconfigure', index, cnf, kw)
  1492. columnconfigure = grid_columnconfigure
  1493. def grid_location(self, x, y):
  1494. """Return a tuple of column and row which identify the cell
  1495. at which the pixel at position X and Y inside the master
  1496. widget is located."""
  1497. return self._getints(
  1498. self.tk.call(
  1499. 'grid', 'location', self._w, x, y)) or None
  1500. def grid_propagate(self, flag=_noarg_):
  1501. """Set or get the status for propagation of geometry information.
  1502. A boolean argument specifies whether the geometry information
  1503. of the slaves will determine the size of this widget. If no argument
  1504. is given, the current setting will be returned.
  1505. """
  1506. if flag is Misc._noarg_:
  1507. return self._getboolean(self.tk.call(
  1508. 'grid', 'propagate', self._w))
  1509. else:
  1510. self.tk.call('grid', 'propagate', self._w, flag)
  1511. def grid_rowconfigure(self, index, cnf={}, **kw):
  1512. """Configure row INDEX of a grid.
  1513. Valid resources are minsize (minimum size of the row),
  1514. weight (how much does additional space propagate to this row)
  1515. and pad (how much space to let additionally)."""
  1516. return self._grid_configure('rowconfigure', index, cnf, kw)
  1517. rowconfigure = grid_rowconfigure
  1518. def grid_size(self):
  1519. """Return a tuple of the number of column and rows in the grid."""
  1520. return self._getints(
  1521. self.tk.call('grid', 'size', self._w)) or None
  1522. size = grid_size
  1523. def grid_slaves(self, row=None, column=None):
  1524. """Return a list of all slaves of this widget
  1525. in its packing order."""
  1526. args = ()
  1527. if row is not None:
  1528. args = args + ('-row', row)
  1529. if column is not None:
  1530. args = args + ('-column', column)
  1531. return [self._nametowidget(x) for x in
  1532. self.tk.splitlist(self.tk.call(
  1533. ('grid', 'slaves', self._w) + args))]
  1534. # Support for the "event" command, new in Tk 4.2.
  1535. # By Case Roole.
  1536. def event_add(self, virtual, *sequences):
  1537. """Bind a virtual event VIRTUAL (of the form <<Name>>)
  1538. to an event SEQUENCE such that the virtual event is triggered
  1539. whenever SEQUENCE occurs."""
  1540. args = ('event', 'add', virtual) + sequences
  1541. self.tk.call(args)
  1542. def event_delete(self, virtual, *sequences):
  1543. """Unbind a virtual event VIRTUAL from SEQUENCE."""
  1544. args = ('event', 'delete', virtual) + sequences
  1545. self.tk.call(args)
  1546. def event_generate(self, sequence, **kw):
  1547. """Generate an event SEQUENCE. Additional
  1548. keyword arguments specify parameter of the event
  1549. (e.g. x, y, rootx, rooty)."""
  1550. args = ('event', 'generate', self._w, sequence)
  1551. for k, v in kw.items():
  1552. args = args + ('-%s' % k, str(v))
  1553. self.tk.call(args)
  1554. def event_info(self, virtual=None):
  1555. """Return a list of all virtual events or the information
  1556. about the SEQUENCE bound to the virtual event VIRTUAL."""
  1557. return self.tk.splitlist(
  1558. self.tk.call('event', 'info', virtual))
  1559. # Image related commands
  1560. def image_names(self):
  1561. """Return a list of all existing image names."""
  1562. return self.tk.splitlist(self.tk.call('image', 'names'))
  1563. def image_types(self):
  1564. """Return a list of all available image types (e.g. photo bitmap)."""
  1565. return self.tk.splitlist(self.tk.call('image', 'types'))
  1566. class CallWrapper:
  1567. """Internal class. Stores function to call when some user
  1568. defined Tcl function is called e.g. after an event occurred."""
  1569. def __init__(self, func, subst, widget):
  1570. """Store FUNC, SUBST and WIDGET as members."""
  1571. self.func = func
  1572. self.subst = subst
  1573. self.widget = widget
  1574. def __call__(self, *args):
  1575. """Apply first function SUBST to arguments, than FUNC."""
  1576. try:
  1577. if self.subst:
  1578. args = self.subst(*args)
  1579. return self.func(*args)
  1580. except SystemExit:
  1581. raise
  1582. except:
  1583. self.widget._report_exception()
  1584. class XView:
  1585. """Mix-in class for querying and changing the horizontal position
  1586. of a widget's window."""
  1587. def xview(self, *args):
  1588. """Query and change the horizontal position of the view."""
  1589. res = self.tk.call(self._w, 'xview', *args)
  1590. if not args:
  1591. return self._getdoubles(res)
  1592. def xview_moveto(self, fraction):
  1593. """Adjusts the view in the window so that FRACTION of the
  1594. total width of the canvas is off-screen to the left."""
  1595. self.tk.call(self._w, 'xview', 'moveto', fraction)
  1596. def xview_scroll(self, number, what):
  1597. """Shift the x-view according to NUMBER which is measured in "units"
  1598. or "pages" (WHAT)."""
  1599. self.tk.call(self._w, 'xview', 'scroll', number, what)
  1600. class YView:
  1601. """Mix-in class for querying and changing the vertical position
  1602. of a widget's window."""
  1603. def yview(self, *args):
  1604. """Query and change the vertical position of the view."""
  1605. res = self.tk.call(self._w, 'yview', *args)
  1606. if not args:
  1607. return self._getdoubles(res)
  1608. def yview_moveto(self, fraction):
  1609. """Adjusts the view in the window so that FRACTION of the
  1610. total height of the canvas is off-screen to the top."""
  1611. self.tk.call(self._w, 'yview', 'moveto', fraction)
  1612. def yview_scroll(self, number, what):
  1613. """Shift the y-view according to NUMBER which is measured in
  1614. "units" or "pages" (WHAT)."""
  1615. self.tk.call(self._w, 'yview', 'scroll', number, what)
  1616. class Wm:
  1617. """Provides functions for the communication with the window manager."""
  1618. def wm_aspect(self,
  1619. minNumer=None, minDenom=None,
  1620. maxNumer=None, maxDenom=None):
  1621. """Instruct the window manager to set the aspect ratio (width/height)
  1622. of this widget to be between MINNUMER/MINDENOM and MAXNUMER/MAXDENOM. Return a tuple
  1623. of the actual values if no argument is given."""
  1624. return self._getints(
  1625. self.tk.call('wm', 'aspect', self._w,
  1626. minNumer, minDenom,
  1627. maxNumer, maxDenom))
  1628. aspect = wm_aspect
  1629. def wm_attributes(self, *args):
  1630. """This subcommand returns or sets platform specific attributes
  1631. The first form returns a list of the platform specific flags and
  1632. their values. The second form returns the value for the specific
  1633. option. The third form sets one or more of the values. The values
  1634. are as follows:
  1635. On Windows, -disabled gets or sets whether the window is in a
  1636. disabled state. -toolwindow gets or sets the style of the window
  1637. to toolwindow (as defined in the MSDN). -topmost gets or sets
  1638. whether this is a topmost window (displays above all other
  1639. windows).
  1640. On Macintosh, XXXXX
  1641. On Unix, there are currently no special attribute values.
  1642. """
  1643. args = ('wm', 'attributes', self._w) + args
  1644. return self.tk.call(args)
  1645. attributes = wm_attributes
  1646. def wm_client(self, name=None):
  1647. """Store NAME in WM_CLIENT_MACHINE property of this widget. Return
  1648. current value."""
  1649. return self.tk.call('wm', 'client', self._w, name)
  1650. client = wm_client
  1651. def wm_colormapwindows(self, *wlist):
  1652. """Store list of window names (WLIST) into WM_COLORMAPWINDOWS property
  1653. of this widget. This list contains windows whose colormaps differ from their
  1654. parents. Return current list of widgets if WLIST is empty."""
  1655. if len(wlist) > 1:
  1656. wlist = (wlist,) # Tk needs a list of windows here
  1657. args = ('wm', 'colormapwindows', self._w) + wlist
  1658. if wlist:
  1659. self.tk.call(args)
  1660. else:
  1661. return [self._nametowidget(x)
  1662. for x in self.tk.splitlist(self.tk.call(args))]
  1663. colormapwindows = wm_colormapwindows
  1664. def wm_command(self, value=None):
  1665. """Store VALUE in WM_COMMAND property. It is the command
  1666. which shall be used to invoke the application. Return current
  1667. command if VALUE is None."""
  1668. return self.tk.call('wm', 'command', self._w, value)
  1669. command = wm_command
  1670. def wm_deiconify(self):
  1671. """Deiconify this widget. If it was never mapped it will not be mapped.
  1672. On Windows it will raise this widget and give it the focus."""
  1673. return self.tk.call('wm', 'deiconify', self._w)
  1674. deiconify = wm_deiconify
  1675. def wm_focusmodel(self, model=None):
  1676. """Set focus model to MODEL. "active" means that this widget will claim
  1677. the focus itself, "passive" means that the window manager shall give
  1678. the focus. Return current focus model if MODEL is None."""
  1679. return self.tk.call('wm', 'focusmodel', self._w, model)
  1680. focusmodel = wm_focusmodel
  1681. def wm_forget(self, window): # new in Tk 8.5
  1682. """The window will be unmapped from the screen and will no longer
  1683. be managed by wm. toplevel windows will be treated like frame
  1684. windows once they are no longer managed by wm, however, the menu
  1685. option configuration will be remembered and the menus will return
  1686. once the widget is managed again."""
  1687. self.tk.call('wm', 'forget', window)
  1688. forget = wm_forget
  1689. def wm_frame(self):
  1690. """Return identifier for decorative frame of this widget if present."""
  1691. return self.tk.call('wm', 'frame', self._w)
  1692. frame = wm_frame
  1693. def wm_geometry(self, newGeometry=None):
  1694. """Set geometry to NEWGEOMETRY of the form =widthxheight+x+y. Return
  1695. current value if None is given."""
  1696. return self.tk.call('wm', 'geometry', self._w, newGeometry)
  1697. geometry = wm_geometry
  1698. def wm_grid(self,
  1699. baseWidth=None, baseHeight=None,
  1700. widthInc=None, heightInc=None):
  1701. """Instruct the window manager that this widget shall only be
  1702. resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and
  1703. height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the
  1704. number of grid units requested in Tk_GeometryRequest."""
  1705. return self._getints(self.tk.call(
  1706. 'wm', 'grid', self._w,
  1707. baseWidth, baseHeight, widthInc, heightInc))
  1708. grid = wm_grid
  1709. def wm_group(self, pathName=None):
  1710. """Set the group leader widgets for related widgets to PATHNAME. Return
  1711. the group leader of this widget if None is given."""
  1712. return self.tk.call('wm', 'group', self._w, pathName)
  1713. group = wm_group
  1714. def wm_iconbitmap(self, bitmap=None, default=None):
  1715. """Set bitmap for the iconified widget to BITMAP. Return
  1716. the bitmap if None is given.
  1717. Under Windows, the DEFAULT parameter can be used to set the icon
  1718. for the widget and any descendents that don't have an icon set
  1719. explicitly. DEFAULT can be the relative path to a .ico file
  1720. (example: root.iconbitmap(default='myicon.ico') ). See Tk
  1721. documentation for more information."""
  1722. if default:
  1723. return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
  1724. else:
  1725. return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
  1726. iconbitmap = wm_iconbitmap
  1727. def wm_iconify(self):
  1728. """Display widget as icon."""
  1729. return self.tk.call('wm', 'iconify', self._w)
  1730. iconify = wm_iconify
  1731. def wm_iconmask(self, bitmap=None):
  1732. """Set mask for the icon bitmap of this widget. Return the
  1733. mask if None is given."""
  1734. return self.tk.call('wm', 'iconmask', self._w, bitmap)
  1735. iconmask = wm_iconmask
  1736. def wm_iconname(self, newName=None):
  1737. """Set the name of the icon for this widget. Return the name if
  1738. None is given."""
  1739. return self.tk.call('wm', 'iconname', self._w, newName)
  1740. iconname = wm_iconname
  1741. def wm_iconphoto(self, default=False, *args): # new in Tk 8.5
  1742. """Sets the titlebar icon for this window based on the named photo
  1743. images passed through args. If default is True, this is applied to
  1744. all future created toplevels as well.
  1745. The data in the images is taken as a snapshot at the time of
  1746. invocation. If the images are later changed, this is not reflected
  1747. to the titlebar icons. Multiple images are accepted to allow
  1748. different images sizes to be provided. The window manager may scale
  1749. provided icons to an appropriate size.
  1750. On Windows, the images are packed into a Windows icon structure.
  1751. This will override an icon specified to wm_iconbitmap, and vice
  1752. versa.
  1753. On X, the images are arranged into the _NET_WM_ICON X property,
  1754. which most modern window managers support. An icon specified by
  1755. wm_iconbitmap may exist simultaneously.
  1756. On Macintosh, this currently does nothing."""
  1757. if default:
  1758. self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
  1759. else:
  1760. self.tk.call('wm', 'iconphoto', self._w, *args)
  1761. iconphoto = wm_iconphoto
  1762. def wm_iconposition(self, x=None, y=None):
  1763. """Set the position of the icon of this widget to X and Y. Return
  1764. a tuple of the current values of X and X if None is given."""
  1765. return self._getints(self.tk.call(
  1766. 'wm', 'iconposition', self._w, x, y))
  1767. iconposition = wm_iconposition
  1768. def wm_iconwindow(self, pathName=None):
  1769. """Set widget PATHNAME to be displayed instead of icon. Return the current
  1770. value if None is given."""
  1771. return self.tk.call('wm', 'iconwindow', self._w, pathName)
  1772. iconwindow = wm_iconwindow
  1773. def wm_manage(self, widget): # new in Tk 8.5
  1774. """The widget specified will become a stand alone top-level window.
  1775. The window will be decorated with the window managers title bar,
  1776. etc."""
  1777. self.tk.call('wm', 'manage', widget)
  1778. manage = wm_manage
  1779. def wm_maxsize(self, width=None, height=None):
  1780. """Set max WIDTH and HEIGHT for this widget. If the window is gridded
  1781. the values are given in grid units. Return the current values if None
  1782. is given."""
  1783. return self._getints(self.tk.call(
  1784. 'wm', 'maxsize', self._w, width, height))
  1785. maxsize = wm_maxsize
  1786. def wm_minsize(self, width=None, height=None):
  1787. """Set min WIDTH and HEIGHT for this widget. If the window is gridded
  1788. the values are given in grid units. Return the current values if None
  1789. is given."""
  1790. return self._getints(self.tk.call(
  1791. 'wm', 'minsize', self._w, width, height))
  1792. minsize = wm_minsize
  1793. def wm_overrideredirect(self, boolean=None):
  1794. """Instruct the window manager to ignore this widget
  1795. if BOOLEAN is given with 1. Return the current value if None
  1796. is given."""
  1797. return self._getboolean(self.tk.call(
  1798. 'wm', 'overrideredirect', self._w, boolean))
  1799. overrideredirect = wm_overrideredirect
  1800. def wm_positionfrom(self, who=None):
  1801. """Instruct the window manager that the position of this widget shall
  1802. be defined by the user if WHO is "user", and by its own policy if WHO is
  1803. "program"."""
  1804. return self.tk.call('wm', 'positionfrom', self._w, who)
  1805. positionfrom = wm_positionfrom
  1806. def wm_protocol(self, name=None, func=None):
  1807. """Bind function FUNC to command NAME for this widget.
  1808. Return the function bound to NAME if None is given. NAME could be
  1809. e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
  1810. if callable(func):
  1811. command = self._register(func)
  1812. else:
  1813. command = func
  1814. return self.tk.call(
  1815. 'wm', 'protocol', self._w, name, command)
  1816. protocol = wm_protocol
  1817. def wm_resizable(self, width=None, height=None):
  1818. """Instruct the window manager whether this width can be resized
  1819. in WIDTH or HEIGHT. Both values are boolean values."""
  1820. return self.tk.call('wm', 'resizable', self._w, width, height)
  1821. resizable = wm_resizable
  1822. def wm_sizefrom(self, who=None):
  1823. """Instruct the window manager that the size of this widget shall
  1824. be defined by the user if WHO is "user", and by its own policy if WHO is
  1825. "program"."""
  1826. return self.tk.call('wm', 'sizefrom', self._w, who)
  1827. sizefrom = wm_sizefrom
  1828. def wm_state(self, newstate=None):
  1829. """Query or set the state of this widget as one of normal, icon,
  1830. iconic (see wm_iconwindow), withdrawn, or zoomed (Windows only)."""
  1831. return self.tk.call('wm', 'state', self._w, newstate)
  1832. state = wm_state
  1833. def wm_title(self, string=None):
  1834. """Set the title of this widget."""
  1835. return self.tk.call('wm', 'title', self._w, string)
  1836. title = wm_title
  1837. def wm_transient(self, master=None):
  1838. """Instruct the window manager that this widget is transient
  1839. with regard to widget MASTER."""
  1840. return self.tk.call('wm', 'transient', self._w, master)
  1841. transient = wm_transient
  1842. def wm_withdraw(self):
  1843. """Withdraw this widget from the screen such that it is unmapped
  1844. and forgotten by the window manager. Re-draw it with wm_deiconify."""
  1845. return self.tk.call('wm', 'withdraw', self._w)
  1846. withdraw = wm_withdraw
  1847. class Tk(Misc, Wm):
  1848. """Toplevel widget of Tk which represents mostly the main window
  1849. of an application. It has an associated Tcl interpreter."""
  1850. _w = '.'
  1851. def __init__(self, screenName=None, baseName=None, className='Tk',
  1852. useTk=True, sync=False, use=None):
  1853. """Return a new Toplevel widget on screen SCREENNAME. A new Tcl interpreter will
  1854. be created. BASENAME will be used for the identification of the profile file (see
  1855. readprofile).
  1856. It is constructed from sys.argv[0] without extensions if None is given. CLASSNAME
  1857. is the name of the widget class."""
  1858. self.master = None
  1859. self.children = {}
  1860. self._tkloaded = False
  1861. # to avoid recursions in the getattr code in case of failure, we
  1862. # ensure that self.tk is always _something_.
  1863. self.tk = None
  1864. if baseName is None:
  1865. import os
  1866. baseName = os.path.basename(sys.argv[0])
  1867. baseName, ext = os.path.splitext(baseName)
  1868. if ext not in ('.py', '.pyc'):
  1869. baseName = baseName + ext
  1870. interactive = False
  1871. self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
  1872. if useTk:
  1873. self._loadtk()
  1874. if not sys.flags.ignore_environment:
  1875. # Issue #16248: Honor the -E flag to avoid code injection.
  1876. self.readprofile(baseName, className)
  1877. def loadtk(self):
  1878. if not self._tkloaded:
  1879. self.tk.loadtk()
  1880. self._loadtk()
  1881. def _loadtk(self):
  1882. self._tkloaded = True
  1883. global _default_root
  1884. # Version sanity checks
  1885. tk_version = self.tk.getvar('tk_version')
  1886. if tk_version != _tkinter.TK_VERSION:
  1887. raise RuntimeError("tk.h version (%s) doesn't match libtk.a version (%s)"
  1888. % (_tkinter.TK_VERSION, tk_version))
  1889. # Under unknown circumstances, tcl_version gets coerced to float
  1890. tcl_version = str(self.tk.getvar('tcl_version'))
  1891. if tcl_version != _tkinter.TCL_VERSION:
  1892. raise RuntimeError("tcl.h version (%s) doesn't match libtcl.a version (%s)" \
  1893. % (_tkinter.TCL_VERSION, tcl_version))
  1894. # Create and register the tkerror and exit commands
  1895. # We need to inline parts of _register here, _ register
  1896. # would register differently-named commands.
  1897. if self._tclCommands is None:
  1898. self._tclCommands = []
  1899. self.tk.createcommand('tkerror', _tkerror)
  1900. self.tk.createcommand('exit', _exit)
  1901. self._tclCommands.append('tkerror')
  1902. self._tclCommands.append('exit')
  1903. if _support_default_root and _default_root is None:
  1904. _default_root = self
  1905. self.protocol("WM_DELETE_WINDOW", self.destroy)
  1906. def destroy(self):
  1907. """Destroy this and all descendants widgets. This will
  1908. end the application of this Tcl interpreter."""
  1909. for c in list(self.children.values()): c.destroy()
  1910. self.tk.call('destroy', self._w)
  1911. Misc.destroy(self)
  1912. global _default_root
  1913. if _support_default_root and _default_root is self:
  1914. _default_root = None
  1915. def readprofile(self, baseName, className):
  1916. """Internal function. It reads BASENAME.tcl and CLASSNAME.tcl into
  1917. the Tcl Interpreter and calls exec on the contents of BASENAME.py and
  1918. CLASSNAME.py if such a file exists in the home directory."""
  1919. import os
  1920. if 'HOME' in os.environ: home = os.environ['HOME']
  1921. else: home = os.curdir
  1922. class_tcl = os.path.join(home, '.%s.tcl' % className)
  1923. class_py = os.path.join(home, '.%s.py' % className)
  1924. base_tcl = os.path.join(home, '.%s.tcl' % baseName)
  1925. base_py = os.path.join(home, '.%s.py' % baseName)
  1926. dir = {'self': self}
  1927. exec('from tkinter import *', dir)
  1928. if os.path.isfile(class_tcl):
  1929. self.tk.call('source', class_tcl)
  1930. if os.path.isfile(class_py):
  1931. exec(open(class_py).read(), dir)
  1932. if os.path.isfile(base_tcl):
  1933. self.tk.call('source', base_tcl)
  1934. if os.path.isfile(base_py):
  1935. exec(open(base_py).read(), dir)
  1936. def report_callback_exception(self, exc, val, tb):
  1937. """Report callback exception on sys.stderr.
  1938. Applications may want to override this internal function, and
  1939. should when sys.stderr is None."""
  1940. import traceback
  1941. print("Exception in Tkinter callback", file=sys.stderr)
  1942. sys.last_type = exc
  1943. sys.last_value = val
  1944. sys.last_traceback = tb
  1945. traceback.print_exception(exc, val, tb)
  1946. def __getattr__(self, attr):
  1947. "Delegate attribute access to the interpreter object"
  1948. return getattr(self.tk, attr)
  1949. # Ideally, the classes Pack, Place and Grid disappear, the
  1950. # pack/place/grid methods are defined on the Widget class, and
  1951. # everybody uses w.pack_whatever(...) instead of Pack.whatever(w,
  1952. # ...), with pack(), place() and grid() being short for
  1953. # pack_configure(), place_configure() and grid_columnconfigure(), and
  1954. # forget() being short for pack_forget(). As a practical matter, I'm
  1955. # afraid that there is too much code out there that may be using the
  1956. # Pack, Place or Grid class, so I leave them intact -- but only as
  1957. # backwards compatibility features. Also note that those methods that
  1958. # take a master as argument (e.g. pack_propagate) have been moved to
  1959. # the Misc class (which now incorporates all methods common between
  1960. # toplevel and interior widgets). Again, for compatibility, these are
  1961. # copied into the Pack, Place or Grid class.
  1962. def Tcl(screenName=None, baseName=None, className='Tk', useTk=False):
  1963. return Tk(screenName, baseName, className, useTk)
  1964. class Pack:
  1965. """Geometry manager Pack.
  1966. Base class to use the methods pack_* in every widget."""
  1967. def pack_configure(self, cnf={}, **kw):
  1968. """Pack a widget in the parent widget. Use as options:
  1969. after=widget - pack it after you have packed widget
  1970. anchor=NSEW (or subset) - position widget according to
  1971. given direction
  1972. before=widget - pack it before you will pack widget
  1973. expand=bool - expand widget if parent size grows
  1974. fill=NONE or X or Y or BOTH - fill widget if widget grows
  1975. in=master - use master to contain this widget
  1976. in_=master - see 'in' option description
  1977. ipadx=amount - add internal padding in x direction
  1978. ipady=amount - add internal padding in y direction
  1979. padx=amount - add padding in x direction
  1980. pady=amount - add padding in y direction
  1981. side=TOP or BOTTOM or LEFT or RIGHT - where to add this widget.
  1982. """
  1983. self.tk.call(
  1984. ('pack', 'configure', self._w)
  1985. + self._options(cnf, kw))
  1986. pack = configure = config = pack_configure
  1987. def pack_forget(self):
  1988. """Unmap this widget and do not use it for the packing order."""
  1989. self.tk.call('pack', 'forget', self._w)
  1990. forget = pack_forget
  1991. def pack_info(self):
  1992. """Return information about the packing options
  1993. for this widget."""
  1994. d = _splitdict(self.tk, self.tk.call('pack', 'info', self._w))
  1995. if 'in' in d:
  1996. d['in'] = self.nametowidget(d['in'])
  1997. return d
  1998. info = pack_info
  1999. propagate = pack_propagate = Misc.pack_propagate
  2000. slaves = pack_slaves = Misc.pack_slaves
  2001. class Place:
  2002. """Geometry manager Place.
  2003. Base class to use the methods place_* in every widget."""
  2004. def place_configure(self, cnf={}, **kw):
  2005. """Place a widget in the parent widget. Use as options:
  2006. in=master - master relative to which the widget is placed
  2007. in_=master - see 'in' option description
  2008. x=amount - locate anchor of this widget at position x of master
  2009. y=amount - locate anchor of this widget at position y of master
  2010. relx=amount - locate anchor of this widget between 0.0 and 1.0
  2011. relative to width of master (1.0 is right edge)
  2012. rely=amount - locate anchor of this widget between 0.0 and 1.0
  2013. relative to height of master (1.0 is bottom edge)
  2014. anchor=NSEW (or subset) - position anchor according to given direction
  2015. width=amount - width of this widget in pixel
  2016. height=amount - height of this widget in pixel
  2017. relwidth=amount - width of this widget between 0.0 and 1.0
  2018. relative to width of master (1.0 is the same width
  2019. as the master)
  2020. relheight=amount - height of this widget between 0.0 and 1.0
  2021. relative to height of master (1.0 is the same
  2022. height as the master)
  2023. bordermode="inside" or "outside" - whether to take border width of
  2024. master widget into account
  2025. """
  2026. self.tk.call(
  2027. ('place', 'configure', self._w)
  2028. + self._options(cnf, kw))
  2029. place = configure = config = place_configure
  2030. def place_forget(self):
  2031. """Unmap this widget."""
  2032. self.tk.call('place', 'forget', self._w)
  2033. forget = place_forget
  2034. def place_info(self):
  2035. """Return information about the placing options
  2036. for this widget."""
  2037. d = _splitdict(self.tk, self.tk.call('place', 'info', self._w))
  2038. if 'in' in d:
  2039. d['in'] = self.nametowidget(d['in'])
  2040. return d
  2041. info = place_info
  2042. slaves = place_slaves = Misc.place_slaves
  2043. class Grid:
  2044. """Geometry manager Grid.
  2045. Base class to use the methods grid_* in every widget."""
  2046. # Thanks to Masazumi Yoshikawa (yosikawa@isi.edu)
  2047. def grid_configure(self, cnf={}, **kw):
  2048. """Position a widget in the parent widget in a grid. Use as options:
  2049. column=number - use cell identified with given column (starting with 0)
  2050. columnspan=number - this widget will span several columns
  2051. in=master - use master to contain this widget
  2052. in_=master - see 'in' option description
  2053. ipadx=amount - add internal padding in x direction
  2054. ipady=amount - add internal padding in y direction
  2055. padx=amount - add padding in x direction
  2056. pady=amount - add padding in y direction
  2057. row=number - use cell identified with given row (starting with 0)
  2058. rowspan=number - this widget will span several rows
  2059. sticky=NSEW - if cell is larger on which sides will this
  2060. widget stick to the cell boundary
  2061. """
  2062. self.tk.call(
  2063. ('grid', 'configure', self._w)
  2064. + self._options(cnf, kw))
  2065. grid = configure = config = grid_configure
  2066. bbox = grid_bbox = Misc.grid_bbox
  2067. columnconfigure = grid_columnconfigure = Misc.grid_columnconfigure
  2068. def grid_forget(self):
  2069. """Unmap this widget."""
  2070. self.tk.call('grid', 'forget', self._w)
  2071. forget = grid_forget
  2072. def grid_remove(self):
  2073. """Unmap this widget but remember the grid options."""
  2074. self.tk.call('grid', 'remove', self._w)
  2075. def grid_info(self):
  2076. """Return information about the options
  2077. for positioning this widget in a grid."""
  2078. d = _splitdict(self.tk, self.tk.call('grid', 'info', self._w))
  2079. if 'in' in d:
  2080. d['in'] = self.nametowidget(d['in'])
  2081. return d
  2082. info = grid_info
  2083. location = grid_location = Misc.grid_location
  2084. propagate = grid_propagate = Misc.grid_propagate
  2085. rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure
  2086. size = grid_size = Misc.grid_size
  2087. slaves = grid_slaves = Misc.grid_slaves
  2088. class BaseWidget(Misc):
  2089. """Internal class."""
  2090. def _setup(self, master, cnf):
  2091. """Internal function. Sets up information about children."""
  2092. if master is None:
  2093. master = _get_default_root()
  2094. self.master = master
  2095. self.tk = master.tk
  2096. name = None
  2097. if 'name' in cnf:
  2098. name = cnf['name']
  2099. del cnf['name']
  2100. if not name:
  2101. name = self.__class__.__name__.lower()
  2102. if master._last_child_ids is None:
  2103. master._last_child_ids = {}
  2104. count = master._last_child_ids.get(name, 0) + 1
  2105. master._last_child_ids[name] = count
  2106. if count == 1:
  2107. name = '!%s' % (name,)
  2108. else:
  2109. name = '!%s%d' % (name, count)
  2110. self._name = name
  2111. if master._w=='.':
  2112. self._w = '.' + name
  2113. else:
  2114. self._w = master._w + '.' + name
  2115. self.children = {}
  2116. if self._name in self.master.children:
  2117. self.master.children[self._name].destroy()
  2118. self.master.children[self._name] = self
  2119. def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
  2120. """Construct a widget with the parent widget MASTER, a name WIDGETNAME
  2121. and appropriate options."""
  2122. if kw:
  2123. cnf = _cnfmerge((cnf, kw))
  2124. self.widgetName = widgetName
  2125. BaseWidget._setup(self, master, cnf)
  2126. if self._tclCommands is None:
  2127. self._tclCommands = []
  2128. classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
  2129. for k, v in classes:
  2130. del cnf[k]
  2131. self.tk.call(
  2132. (widgetName, self._w) + extra + self._options(cnf))
  2133. for k, v in classes:
  2134. k.configure(self, v)
  2135. def destroy(self):
  2136. """Destroy this and all descendants widgets."""
  2137. for c in list(self.children.values()): c.destroy()
  2138. self.tk.call('destroy', self._w)
  2139. if self._name in self.master.children:
  2140. del self.master.children[self._name]
  2141. Misc.destroy(self)
  2142. def _do(self, name, args=()):
  2143. # XXX Obsolete -- better use self.tk.call directly!
  2144. return self.tk.call((self._w, name) + args)
  2145. class Widget(BaseWidget, Pack, Place, Grid):
  2146. """Internal class.
  2147. Base class for a widget which can be positioned with the geometry managers
  2148. Pack, Place or Grid."""
  2149. pass
  2150. class Toplevel(BaseWidget, Wm):
  2151. """Toplevel widget, e.g. for dialogs."""
  2152. def __init__(self, master=None, cnf={}, **kw):
  2153. """Construct a toplevel widget with the parent MASTER.
  2154. Valid resource names: background, bd, bg, borderwidth, class,
  2155. colormap, container, cursor, height, highlightbackground,
  2156. highlightcolor, highlightthickness, menu, relief, screen, takefocus,
  2157. use, visual, width."""
  2158. if kw:
  2159. cnf = _cnfmerge((cnf, kw))
  2160. extra = ()
  2161. for wmkey in ['screen', 'class_', 'class', 'visual',
  2162. 'colormap']:
  2163. if wmkey in cnf:
  2164. val = cnf[wmkey]
  2165. # TBD: a hack needed because some keys
  2166. # are not valid as keyword arguments
  2167. if wmkey[-1] == '_': opt = '-'+wmkey[:-1]
  2168. else: opt = '-'+wmkey
  2169. extra = extra + (opt, val)
  2170. del cnf[wmkey]
  2171. BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
  2172. root = self._root()
  2173. self.iconname(root.iconname())
  2174. self.title(root.title())
  2175. self.protocol("WM_DELETE_WINDOW", self.destroy)
  2176. class Button(Widget):
  2177. """Button widget."""
  2178. def __init__(self, master=None, cnf={}, **kw):
  2179. """Construct a button widget with the parent MASTER.
  2180. STANDARD OPTIONS
  2181. activebackground, activeforeground, anchor,
  2182. background, bitmap, borderwidth, cursor,
  2183. disabledforeground, font, foreground
  2184. highlightbackground, highlightcolor,
  2185. highlightthickness, image, justify,
  2186. padx, pady, relief, repeatdelay,
  2187. repeatinterval, takefocus, text,
  2188. textvariable, underline, wraplength
  2189. WIDGET-SPECIFIC OPTIONS
  2190. command, compound, default, height,
  2191. overrelief, state, width
  2192. """
  2193. Widget.__init__(self, master, 'button', cnf, kw)
  2194. def flash(self):
  2195. """Flash the button.
  2196. This is accomplished by redisplaying
  2197. the button several times, alternating between active and
  2198. normal colors. At the end of the flash the button is left
  2199. in the same normal/active state as when the command was
  2200. invoked. This command is ignored if the button's state is
  2201. disabled.
  2202. """
  2203. self.tk.call(self._w, 'flash')
  2204. def invoke(self):
  2205. """Invoke the command associated with the button.
  2206. The return value is the return value from the command,
  2207. or an empty string if there is no command associated with
  2208. the button. This command is ignored if the button's state
  2209. is disabled.
  2210. """
  2211. return self.tk.call(self._w, 'invoke')
  2212. class Canvas(Widget, XView, YView):
  2213. """Canvas widget to display graphical elements like lines or text."""
  2214. def __init__(self, master=None, cnf={}, **kw):
  2215. """Construct a canvas widget with the parent MASTER.
  2216. Valid resource names: background, bd, bg, borderwidth, closeenough,
  2217. confine, cursor, height, highlightbackground, highlightcolor,
  2218. highlightthickness, insertbackground, insertborderwidth,
  2219. insertofftime, insertontime, insertwidth, offset, relief,
  2220. scrollregion, selectbackground, selectborderwidth, selectforeground,
  2221. state, takefocus, width, xscrollcommand, xscrollincrement,
  2222. yscrollcommand, yscrollincrement."""
  2223. Widget.__init__(self, master, 'canvas', cnf, kw)
  2224. def addtag(self, *args):
  2225. """Internal function."""
  2226. self.tk.call((self._w, 'addtag') + args)
  2227. def addtag_above(self, newtag, tagOrId):
  2228. """Add tag NEWTAG to all items above TAGORID."""
  2229. self.addtag(newtag, 'above', tagOrId)
  2230. def addtag_all(self, newtag):
  2231. """Add tag NEWTAG to all items."""
  2232. self.addtag(newtag, 'all')
  2233. def addtag_below(self, newtag, tagOrId):
  2234. """Add tag NEWTAG to all items below TAGORID."""
  2235. self.addtag(newtag, 'below', tagOrId)
  2236. def addtag_closest(self, newtag, x, y, halo=None, start=None):
  2237. """Add tag NEWTAG to item which is closest to pixel at X, Y.
  2238. If several match take the top-most.
  2239. All items closer than HALO are considered overlapping (all are
  2240. closests). If START is specified the next below this tag is taken."""
  2241. self.addtag(newtag, 'closest', x, y, halo, start)
  2242. def addtag_enclosed(self, newtag, x1, y1, x2, y2):
  2243. """Add tag NEWTAG to all items in the rectangle defined
  2244. by X1,Y1,X2,Y2."""
  2245. self.addtag(newtag, 'enclosed', x1, y1, x2, y2)
  2246. def addtag_overlapping(self, newtag, x1, y1, x2, y2):
  2247. """Add tag NEWTAG to all items which overlap the rectangle
  2248. defined by X1,Y1,X2,Y2."""
  2249. self.addtag(newtag, 'overlapping', x1, y1, x2, y2)
  2250. def addtag_withtag(self, newtag, tagOrId):
  2251. """Add tag NEWTAG to all items with TAGORID."""
  2252. self.addtag(newtag, 'withtag', tagOrId)
  2253. def bbox(self, *args):
  2254. """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2255. which encloses all items with tags specified as arguments."""
  2256. return self._getints(
  2257. self.tk.call((self._w, 'bbox') + args)) or None
  2258. def tag_unbind(self, tagOrId, sequence, funcid=None):
  2259. """Unbind for all items with TAGORID for event SEQUENCE the
  2260. function identified with FUNCID."""
  2261. self.tk.call(self._w, 'bind', tagOrId, sequence, '')
  2262. if funcid:
  2263. self.deletecommand(funcid)
  2264. def tag_bind(self, tagOrId, sequence=None, func=None, add=None):
  2265. """Bind to all items with TAGORID at event SEQUENCE a call to function FUNC.
  2266. An additional boolean parameter ADD specifies whether FUNC will be
  2267. called additionally to the other bound function or whether it will
  2268. replace the previous function. See bind for the return value."""
  2269. return self._bind((self._w, 'bind', tagOrId),
  2270. sequence, func, add)
  2271. def canvasx(self, screenx, gridspacing=None):
  2272. """Return the canvas x coordinate of pixel position SCREENX rounded
  2273. to nearest multiple of GRIDSPACING units."""
  2274. return self.tk.getdouble(self.tk.call(
  2275. self._w, 'canvasx', screenx, gridspacing))
  2276. def canvasy(self, screeny, gridspacing=None):
  2277. """Return the canvas y coordinate of pixel position SCREENY rounded
  2278. to nearest multiple of GRIDSPACING units."""
  2279. return self.tk.getdouble(self.tk.call(
  2280. self._w, 'canvasy', screeny, gridspacing))
  2281. def coords(self, *args):
  2282. """Return a list of coordinates for the item given in ARGS."""
  2283. # XXX Should use _flatten on args
  2284. return [self.tk.getdouble(x) for x in
  2285. self.tk.splitlist(
  2286. self.tk.call((self._w, 'coords') + args))]
  2287. def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
  2288. """Internal function."""
  2289. args = _flatten(args)
  2290. cnf = args[-1]
  2291. if isinstance(cnf, (dict, tuple)):
  2292. args = args[:-1]
  2293. else:
  2294. cnf = {}
  2295. return self.tk.getint(self.tk.call(
  2296. self._w, 'create', itemType,
  2297. *(args + self._options(cnf, kw))))
  2298. def create_arc(self, *args, **kw):
  2299. """Create arc shaped region with coordinates x1,y1,x2,y2."""
  2300. return self._create('arc', args, kw)
  2301. def create_bitmap(self, *args, **kw):
  2302. """Create bitmap with coordinates x1,y1."""
  2303. return self._create('bitmap', args, kw)
  2304. def create_image(self, *args, **kw):
  2305. """Create image item with coordinates x1,y1."""
  2306. return self._create('image', args, kw)
  2307. def create_line(self, *args, **kw):
  2308. """Create line with coordinates x1,y1,...,xn,yn."""
  2309. return self._create('line', args, kw)
  2310. def create_oval(self, *args, **kw):
  2311. """Create oval with coordinates x1,y1,x2,y2."""
  2312. return self._create('oval', args, kw)
  2313. def create_polygon(self, *args, **kw):
  2314. """Create polygon with coordinates x1,y1,...,xn,yn."""
  2315. return self._create('polygon', args, kw)
  2316. def create_rectangle(self, *args, **kw):
  2317. """Create rectangle with coordinates x1,y1,x2,y2."""
  2318. return self._create('rectangle', args, kw)
  2319. def create_text(self, *args, **kw):
  2320. """Create text with coordinates x1,y1."""
  2321. return self._create('text', args, kw)
  2322. def create_window(self, *args, **kw):
  2323. """Create window with coordinates x1,y1,x2,y2."""
  2324. return self._create('window', args, kw)
  2325. def dchars(self, *args):
  2326. """Delete characters of text items identified by tag or id in ARGS (possibly
  2327. several times) from FIRST to LAST character (including)."""
  2328. self.tk.call((self._w, 'dchars') + args)
  2329. def delete(self, *args):
  2330. """Delete items identified by all tag or ids contained in ARGS."""
  2331. self.tk.call((self._w, 'delete') + args)
  2332. def dtag(self, *args):
  2333. """Delete tag or id given as last arguments in ARGS from items
  2334. identified by first argument in ARGS."""
  2335. self.tk.call((self._w, 'dtag') + args)
  2336. def find(self, *args):
  2337. """Internal function."""
  2338. return self._getints(
  2339. self.tk.call((self._w, 'find') + args)) or ()
  2340. def find_above(self, tagOrId):
  2341. """Return items above TAGORID."""
  2342. return self.find('above', tagOrId)
  2343. def find_all(self):
  2344. """Return all items."""
  2345. return self.find('all')
  2346. def find_below(self, tagOrId):
  2347. """Return all items below TAGORID."""
  2348. return self.find('below', tagOrId)
  2349. def find_closest(self, x, y, halo=None, start=None):
  2350. """Return item which is closest to pixel at X, Y.
  2351. If several match take the top-most.
  2352. All items closer than HALO are considered overlapping (all are
  2353. closest). If START is specified the next below this tag is taken."""
  2354. return self.find('closest', x, y, halo, start)
  2355. def find_enclosed(self, x1, y1, x2, y2):
  2356. """Return all items in rectangle defined
  2357. by X1,Y1,X2,Y2."""
  2358. return self.find('enclosed', x1, y1, x2, y2)
  2359. def find_overlapping(self, x1, y1, x2, y2):
  2360. """Return all items which overlap the rectangle
  2361. defined by X1,Y1,X2,Y2."""
  2362. return self.find('overlapping', x1, y1, x2, y2)
  2363. def find_withtag(self, tagOrId):
  2364. """Return all items with TAGORID."""
  2365. return self.find('withtag', tagOrId)
  2366. def focus(self, *args):
  2367. """Set focus to the first item specified in ARGS."""
  2368. return self.tk.call((self._w, 'focus') + args)
  2369. def gettags(self, *args):
  2370. """Return tags associated with the first item specified in ARGS."""
  2371. return self.tk.splitlist(
  2372. self.tk.call((self._w, 'gettags') + args))
  2373. def icursor(self, *args):
  2374. """Set cursor at position POS in the item identified by TAGORID.
  2375. In ARGS TAGORID must be first."""
  2376. self.tk.call((self._w, 'icursor') + args)
  2377. def index(self, *args):
  2378. """Return position of cursor as integer in item specified in ARGS."""
  2379. return self.tk.getint(self.tk.call((self._w, 'index') + args))
  2380. def insert(self, *args):
  2381. """Insert TEXT in item TAGORID at position POS. ARGS must
  2382. be TAGORID POS TEXT."""
  2383. self.tk.call((self._w, 'insert') + args)
  2384. def itemcget(self, tagOrId, option):
  2385. """Return the resource value for an OPTION for item TAGORID."""
  2386. return self.tk.call(
  2387. (self._w, 'itemcget') + (tagOrId, '-'+option))
  2388. def itemconfigure(self, tagOrId, cnf=None, **kw):
  2389. """Configure resources of an item TAGORID.
  2390. The values for resources are specified as keyword
  2391. arguments. To get an overview about
  2392. the allowed keyword arguments call the method without arguments.
  2393. """
  2394. return self._configure(('itemconfigure', tagOrId), cnf, kw)
  2395. itemconfig = itemconfigure
  2396. # lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
  2397. # so the preferred name for them is tag_lower, tag_raise
  2398. # (similar to tag_bind, and similar to the Text widget);
  2399. # unfortunately can't delete the old ones yet (maybe in 1.6)
  2400. def tag_lower(self, *args):
  2401. """Lower an item TAGORID given in ARGS
  2402. (optional below another item)."""
  2403. self.tk.call((self._w, 'lower') + args)
  2404. lower = tag_lower
  2405. def move(self, *args):
  2406. """Move an item TAGORID given in ARGS."""
  2407. self.tk.call((self._w, 'move') + args)
  2408. def moveto(self, tagOrId, x='', y=''):
  2409. """Move the items given by TAGORID in the canvas coordinate
  2410. space so that the first coordinate pair of the bottommost
  2411. item with tag TAGORID is located at position (X,Y).
  2412. X and Y may be the empty string, in which case the
  2413. corresponding coordinate will be unchanged. All items matching
  2414. TAGORID remain in the same positions relative to each other."""
  2415. self.tk.call(self._w, 'moveto', tagOrId, x, y)
  2416. def postscript(self, cnf={}, **kw):
  2417. """Print the contents of the canvas to a postscript
  2418. file. Valid options: colormap, colormode, file, fontmap,
  2419. height, pageanchor, pageheight, pagewidth, pagex, pagey,
  2420. rotate, width, x, y."""
  2421. return self.tk.call((self._w, 'postscript') +
  2422. self._options(cnf, kw))
  2423. def tag_raise(self, *args):
  2424. """Raise an item TAGORID given in ARGS
  2425. (optional above another item)."""
  2426. self.tk.call((self._w, 'raise') + args)
  2427. lift = tkraise = tag_raise
  2428. def scale(self, *args):
  2429. """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE."""
  2430. self.tk.call((self._w, 'scale') + args)
  2431. def scan_mark(self, x, y):
  2432. """Remember the current X, Y coordinates."""
  2433. self.tk.call(self._w, 'scan', 'mark', x, y)
  2434. def scan_dragto(self, x, y, gain=10):
  2435. """Adjust the view of the canvas to GAIN times the
  2436. difference between X and Y and the coordinates given in
  2437. scan_mark."""
  2438. self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
  2439. def select_adjust(self, tagOrId, index):
  2440. """Adjust the end of the selection near the cursor of an item TAGORID to index."""
  2441. self.tk.call(self._w, 'select', 'adjust', tagOrId, index)
  2442. def select_clear(self):
  2443. """Clear the selection if it is in this widget."""
  2444. self.tk.call(self._w, 'select', 'clear')
  2445. def select_from(self, tagOrId, index):
  2446. """Set the fixed end of a selection in item TAGORID to INDEX."""
  2447. self.tk.call(self._w, 'select', 'from', tagOrId, index)
  2448. def select_item(self):
  2449. """Return the item which has the selection."""
  2450. return self.tk.call(self._w, 'select', 'item') or None
  2451. def select_to(self, tagOrId, index):
  2452. """Set the variable end of a selection in item TAGORID to INDEX."""
  2453. self.tk.call(self._w, 'select', 'to', tagOrId, index)
  2454. def type(self, tagOrId):
  2455. """Return the type of the item TAGORID."""
  2456. return self.tk.call(self._w, 'type', tagOrId) or None
  2457. class Checkbutton(Widget):
  2458. """Checkbutton widget which is either in on- or off-state."""
  2459. def __init__(self, master=None, cnf={}, **kw):
  2460. """Construct a checkbutton widget with the parent MASTER.
  2461. Valid resource names: activebackground, activeforeground, anchor,
  2462. background, bd, bg, bitmap, borderwidth, command, cursor,
  2463. disabledforeground, fg, font, foreground, height,
  2464. highlightbackground, highlightcolor, highlightthickness, image,
  2465. indicatoron, justify, offvalue, onvalue, padx, pady, relief,
  2466. selectcolor, selectimage, state, takefocus, text, textvariable,
  2467. underline, variable, width, wraplength."""
  2468. Widget.__init__(self, master, 'checkbutton', cnf, kw)
  2469. def deselect(self):
  2470. """Put the button in off-state."""
  2471. self.tk.call(self._w, 'deselect')
  2472. def flash(self):
  2473. """Flash the button."""
  2474. self.tk.call(self._w, 'flash')
  2475. def invoke(self):
  2476. """Toggle the button and invoke a command if given as resource."""
  2477. return self.tk.call(self._w, 'invoke')
  2478. def select(self):
  2479. """Put the button in on-state."""
  2480. self.tk.call(self._w, 'select')
  2481. def toggle(self):
  2482. """Toggle the button."""
  2483. self.tk.call(self._w, 'toggle')
  2484. class Entry(Widget, XView):
  2485. """Entry widget which allows displaying simple text."""
  2486. def __init__(self, master=None, cnf={}, **kw):
  2487. """Construct an entry widget with the parent MASTER.
  2488. Valid resource names: background, bd, bg, borderwidth, cursor,
  2489. exportselection, fg, font, foreground, highlightbackground,
  2490. highlightcolor, highlightthickness, insertbackground,
  2491. insertborderwidth, insertofftime, insertontime, insertwidth,
  2492. invalidcommand, invcmd, justify, relief, selectbackground,
  2493. selectborderwidth, selectforeground, show, state, takefocus,
  2494. textvariable, validate, validatecommand, vcmd, width,
  2495. xscrollcommand."""
  2496. Widget.__init__(self, master, 'entry', cnf, kw)
  2497. def delete(self, first, last=None):
  2498. """Delete text from FIRST to LAST (not included)."""
  2499. self.tk.call(self._w, 'delete', first, last)
  2500. def get(self):
  2501. """Return the text."""
  2502. return self.tk.call(self._w, 'get')
  2503. def icursor(self, index):
  2504. """Insert cursor at INDEX."""
  2505. self.tk.call(self._w, 'icursor', index)
  2506. def index(self, index):
  2507. """Return position of cursor."""
  2508. return self.tk.getint(self.tk.call(
  2509. self._w, 'index', index))
  2510. def insert(self, index, string):
  2511. """Insert STRING at INDEX."""
  2512. self.tk.call(self._w, 'insert', index, string)
  2513. def scan_mark(self, x):
  2514. """Remember the current X, Y coordinates."""
  2515. self.tk.call(self._w, 'scan', 'mark', x)
  2516. def scan_dragto(self, x):
  2517. """Adjust the view of the canvas to 10 times the
  2518. difference between X and Y and the coordinates given in
  2519. scan_mark."""
  2520. self.tk.call(self._w, 'scan', 'dragto', x)
  2521. def selection_adjust(self, index):
  2522. """Adjust the end of the selection near the cursor to INDEX."""
  2523. self.tk.call(self._w, 'selection', 'adjust', index)
  2524. select_adjust = selection_adjust
  2525. def selection_clear(self):
  2526. """Clear the selection if it is in this widget."""
  2527. self.tk.call(self._w, 'selection', 'clear')
  2528. select_clear = selection_clear
  2529. def selection_from(self, index):
  2530. """Set the fixed end of a selection to INDEX."""
  2531. self.tk.call(self._w, 'selection', 'from', index)
  2532. select_from = selection_from
  2533. def selection_present(self):
  2534. """Return True if there are characters selected in the entry, False
  2535. otherwise."""
  2536. return self.tk.getboolean(
  2537. self.tk.call(self._w, 'selection', 'present'))
  2538. select_present = selection_present
  2539. def selection_range(self, start, end):
  2540. """Set the selection from START to END (not included)."""
  2541. self.tk.call(self._w, 'selection', 'range', start, end)
  2542. select_range = selection_range
  2543. def selection_to(self, index):
  2544. """Set the variable end of a selection to INDEX."""
  2545. self.tk.call(self._w, 'selection', 'to', index)
  2546. select_to = selection_to
  2547. class Frame(Widget):
  2548. """Frame widget which may contain other widgets and can have a 3D border."""
  2549. def __init__(self, master=None, cnf={}, **kw):
  2550. """Construct a frame widget with the parent MASTER.
  2551. Valid resource names: background, bd, bg, borderwidth, class,
  2552. colormap, container, cursor, height, highlightbackground,
  2553. highlightcolor, highlightthickness, relief, takefocus, visual, width."""
  2554. cnf = _cnfmerge((cnf, kw))
  2555. extra = ()
  2556. if 'class_' in cnf:
  2557. extra = ('-class', cnf['class_'])
  2558. del cnf['class_']
  2559. elif 'class' in cnf:
  2560. extra = ('-class', cnf['class'])
  2561. del cnf['class']
  2562. Widget.__init__(self, master, 'frame', cnf, {}, extra)
  2563. class Label(Widget):
  2564. """Label widget which can display text and bitmaps."""
  2565. def __init__(self, master=None, cnf={}, **kw):
  2566. """Construct a label widget with the parent MASTER.
  2567. STANDARD OPTIONS
  2568. activebackground, activeforeground, anchor,
  2569. background, bitmap, borderwidth, cursor,
  2570. disabledforeground, font, foreground,
  2571. highlightbackground, highlightcolor,
  2572. highlightthickness, image, justify,
  2573. padx, pady, relief, takefocus, text,
  2574. textvariable, underline, wraplength
  2575. WIDGET-SPECIFIC OPTIONS
  2576. height, state, width
  2577. """
  2578. Widget.__init__(self, master, 'label', cnf, kw)
  2579. class Listbox(Widget, XView, YView):
  2580. """Listbox widget which can display a list of strings."""
  2581. def __init__(self, master=None, cnf={}, **kw):
  2582. """Construct a listbox widget with the parent MASTER.
  2583. Valid resource names: background, bd, bg, borderwidth, cursor,
  2584. exportselection, fg, font, foreground, height, highlightbackground,
  2585. highlightcolor, highlightthickness, relief, selectbackground,
  2586. selectborderwidth, selectforeground, selectmode, setgrid, takefocus,
  2587. width, xscrollcommand, yscrollcommand, listvariable."""
  2588. Widget.__init__(self, master, 'listbox', cnf, kw)
  2589. def activate(self, index):
  2590. """Activate item identified by INDEX."""
  2591. self.tk.call(self._w, 'activate', index)
  2592. def bbox(self, index):
  2593. """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle
  2594. which encloses the item identified by the given index."""
  2595. return self._getints(self.tk.call(self._w, 'bbox', index)) or None
  2596. def curselection(self):
  2597. """Return the indices of currently selected item."""
  2598. return self._getints(self.tk.call(self._w, 'curselection')) or ()
  2599. def delete(self, first, last=None):
  2600. """Delete items from FIRST to LAST (included)."""
  2601. self.tk.call(self._w, 'delete', first, last)
  2602. def get(self, first, last=None):
  2603. """Get list of items from FIRST to LAST (included)."""
  2604. if last is not None:
  2605. return self.tk.splitlist(self.tk.call(
  2606. self._w, 'get', first, last))
  2607. else:
  2608. return self.tk.call(self._w, 'get', first)
  2609. def index(self, index):
  2610. """Return index of item identified with INDEX."""
  2611. i = self.tk.call(self._w, 'index', index)
  2612. if i == 'none': return None
  2613. return self.tk.getint(i)
  2614. def insert(self, index, *elements):
  2615. """Insert ELEMENTS at INDEX."""
  2616. self.tk.call((self._w, 'insert', index) + elements)
  2617. def nearest(self, y):
  2618. """Get index of item which is nearest to y coordinate Y."""
  2619. return self.tk.getint(self.tk.call(
  2620. self._w, 'nearest', y))
  2621. def scan_mark(self, x, y):
  2622. """Remember the current X, Y coordinates."""
  2623. self.tk.call(self._w, 'scan', 'mark', x, y)
  2624. def scan_dragto(self, x, y):
  2625. """Adjust the view of the listbox to 10 times the
  2626. difference between X and Y and the coordinates given in
  2627. scan_mark."""
  2628. self.tk.call(self._w, 'scan', 'dragto', x, y)
  2629. def see(self, index):
  2630. """Scroll such that INDEX is visible."""
  2631. self.tk.call(self._w, 'see', index)
  2632. def selection_anchor(self, index):
  2633. """Set the fixed end oft the selection to INDEX."""
  2634. self.tk.call(self._w, 'selection', 'anchor', index)
  2635. select_anchor = selection_anchor
  2636. def selection_clear(self, first, last=None):
  2637. """Clear the selection from FIRST to LAST (included)."""
  2638. self.tk.call(self._w,
  2639. 'selection', 'clear', first, last)
  2640. select_clear = selection_clear
  2641. def selection_includes(self, index):
  2642. """Return True if INDEX is part of the selection."""
  2643. return self.tk.getboolean(self.tk.call(
  2644. self._w, 'selection', 'includes', index))
  2645. select_includes = selection_includes
  2646. def selection_set(self, first, last=None):
  2647. """Set the selection from FIRST to LAST (included) without
  2648. changing the currently selected elements."""
  2649. self.tk.call(self._w, 'selection', 'set', first, last)
  2650. select_set = selection_set
  2651. def size(self):
  2652. """Return the number of elements in the listbox."""
  2653. return self.tk.getint(self.tk.call(self._w, 'size'))
  2654. def itemcget(self, index, option):
  2655. """Return the resource value for an ITEM and an OPTION."""
  2656. return self.tk.call(
  2657. (self._w, 'itemcget') + (index, '-'+option))
  2658. def itemconfigure(self, index, cnf=None, **kw):
  2659. """Configure resources of an ITEM.
  2660. The values for resources are specified as keyword arguments.
  2661. To get an overview about the allowed keyword arguments
  2662. call the method without arguments.
  2663. Valid resource names: background, bg, foreground, fg,
  2664. selectbackground, selectforeground."""
  2665. return self._configure(('itemconfigure', index), cnf, kw)
  2666. itemconfig = itemconfigure
  2667. class Menu(Widget):
  2668. """Menu widget which allows displaying menu bars, pull-down menus and pop-up menus."""
  2669. def __init__(self, master=None, cnf={}, **kw):
  2670. """Construct menu widget with the parent MASTER.
  2671. Valid resource names: activebackground, activeborderwidth,
  2672. activeforeground, background, bd, bg, borderwidth, cursor,
  2673. disabledforeground, fg, font, foreground, postcommand, relief,
  2674. selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
  2675. Widget.__init__(self, master, 'menu', cnf, kw)
  2676. def tk_popup(self, x, y, entry=""):
  2677. """Post the menu at position X,Y with entry ENTRY."""
  2678. self.tk.call('tk_popup', self._w, x, y, entry)
  2679. def activate(self, index):
  2680. """Activate entry at INDEX."""
  2681. self.tk.call(self._w, 'activate', index)
  2682. def add(self, itemType, cnf={}, **kw):
  2683. """Internal function."""
  2684. self.tk.call((self._w, 'add', itemType) +
  2685. self._options(cnf, kw))
  2686. def add_cascade(self, cnf={}, **kw):
  2687. """Add hierarchical menu item."""
  2688. self.add('cascade', cnf or kw)
  2689. def add_checkbutton(self, cnf={}, **kw):
  2690. """Add checkbutton menu item."""
  2691. self.add('checkbutton', cnf or kw)
  2692. def add_command(self, cnf={}, **kw):
  2693. """Add command menu item."""
  2694. self.add('command', cnf or kw)
  2695. def add_radiobutton(self, cnf={}, **kw):
  2696. """Addd radio menu item."""
  2697. self.add('radiobutton', cnf or kw)
  2698. def add_separator(self, cnf={}, **kw):
  2699. """Add separator."""
  2700. self.add('separator', cnf or kw)
  2701. def insert(self, index, itemType, cnf={}, **kw):
  2702. """Internal function."""
  2703. self.tk.call((self._w, 'insert', index, itemType) +
  2704. self._options(cnf, kw))
  2705. def insert_cascade(self, index, cnf={}, **kw):
  2706. """Add hierarchical menu item at INDEX."""
  2707. self.insert(index, 'cascade', cnf or kw)
  2708. def insert_checkbutton(self, index, cnf={}, **kw):
  2709. """Add checkbutton menu item at INDEX."""
  2710. self.insert(index, 'checkbutton', cnf or kw)
  2711. def insert_command(self, index, cnf={}, **kw):
  2712. """Add command menu item at INDEX."""
  2713. self.insert(index, 'command', cnf or kw)
  2714. def insert_radiobutton(self, index, cnf={}, **kw):
  2715. """Addd radio menu item at INDEX."""
  2716. self.insert(index, 'radiobutton', cnf or kw)
  2717. def insert_separator(self, index, cnf={}, **kw):
  2718. """Add separator at INDEX."""
  2719. self.insert(index, 'separator', cnf or kw)
  2720. def delete(self, index1, index2=None):
  2721. """Delete menu items between INDEX1 and INDEX2 (included)."""
  2722. if index2 is None:
  2723. index2 = index1
  2724. num_index1, num_index2 = self.index(index1), self.index(index2)
  2725. if (num_index1 is None) or (num_index2 is None):
  2726. num_index1, num_index2 = 0, -1
  2727. for i in range(num_index1, num_index2 + 1):
  2728. if 'command' in self.entryconfig(i):
  2729. c = str(self.entrycget(i, 'command'))
  2730. if c:
  2731. self.deletecommand(c)
  2732. self.tk.call(self._w, 'delete', index1, index2)
  2733. def entrycget(self, index, option):
  2734. """Return the resource value of a menu item for OPTION at INDEX."""
  2735. return self.tk.call(self._w, 'entrycget', index, '-' + option)
  2736. def entryconfigure(self, index, cnf=None, **kw):
  2737. """Configure a menu item at INDEX."""
  2738. return self._configure(('entryconfigure', index), cnf, kw)
  2739. entryconfig = entryconfigure
  2740. def index(self, index):
  2741. """Return the index of a menu item identified by INDEX."""
  2742. i = self.tk.call(self._w, 'index', index)
  2743. if i == 'none': return None
  2744. return self.tk.getint(i)
  2745. def invoke(self, index):
  2746. """Invoke a menu item identified by INDEX and execute
  2747. the associated command."""
  2748. return self.tk.call(self._w, 'invoke', index)
  2749. def post(self, x, y):
  2750. """Display a menu at position X,Y."""
  2751. self.tk.call(self._w, 'post', x, y)
  2752. def type(self, index):
  2753. """Return the type of the menu item at INDEX."""
  2754. return self.tk.call(self._w, 'type', index)
  2755. def unpost(self):
  2756. """Unmap a menu."""
  2757. self.tk.call(self._w, 'unpost')
  2758. def xposition(self, index): # new in Tk 8.5
  2759. """Return the x-position of the leftmost pixel of the menu item
  2760. at INDEX."""
  2761. return self.tk.getint(self.tk.call(self._w, 'xposition', index))
  2762. def yposition(self, index):
  2763. """Return the y-position of the topmost pixel of the menu item at INDEX."""
  2764. return self.tk.getint(self.tk.call(
  2765. self._w, 'yposition', index))
  2766. class Menubutton(Widget):
  2767. """Menubutton widget, obsolete since Tk8.0."""
  2768. def __init__(self, master=None, cnf={}, **kw):
  2769. Widget.__init__(self, master, 'menubutton', cnf, kw)
  2770. class Message(Widget):
  2771. """Message widget to display multiline text. Obsolete since Label does it too."""
  2772. def __init__(self, master=None, cnf={}, **kw):
  2773. Widget.__init__(self, master, 'message', cnf, kw)
  2774. class Radiobutton(Widget):
  2775. """Radiobutton widget which shows only one of several buttons in on-state."""
  2776. def __init__(self, master=None, cnf={}, **kw):
  2777. """Construct a radiobutton widget with the parent MASTER.
  2778. Valid resource names: activebackground, activeforeground, anchor,
  2779. background, bd, bg, bitmap, borderwidth, command, cursor,
  2780. disabledforeground, fg, font, foreground, height,
  2781. highlightbackground, highlightcolor, highlightthickness, image,
  2782. indicatoron, justify, padx, pady, relief, selectcolor, selectimage,
  2783. state, takefocus, text, textvariable, underline, value, variable,
  2784. width, wraplength."""
  2785. Widget.__init__(self, master, 'radiobutton', cnf, kw)
  2786. def deselect(self):
  2787. """Put the button in off-state."""
  2788. self.tk.call(self._w, 'deselect')
  2789. def flash(self):
  2790. """Flash the button."""
  2791. self.tk.call(self._w, 'flash')
  2792. def invoke(self):
  2793. """Toggle the button and invoke a command if given as resource."""
  2794. return self.tk.call(self._w, 'invoke')
  2795. def select(self):
  2796. """Put the button in on-state."""
  2797. self.tk.call(self._w, 'select')
  2798. class Scale(Widget):
  2799. """Scale widget which can display a numerical scale."""
  2800. def __init__(self, master=None, cnf={}, **kw):
  2801. """Construct a scale widget with the parent MASTER.
  2802. Valid resource names: activebackground, background, bigincrement, bd,
  2803. bg, borderwidth, command, cursor, digits, fg, font, foreground, from,
  2804. highlightbackground, highlightcolor, highlightthickness, label,
  2805. length, orient, relief, repeatdelay, repeatinterval, resolution,
  2806. showvalue, sliderlength, sliderrelief, state, takefocus,
  2807. tickinterval, to, troughcolor, variable, width."""
  2808. Widget.__init__(self, master, 'scale', cnf, kw)
  2809. def get(self):
  2810. """Get the current value as integer or float."""
  2811. value = self.tk.call(self._w, 'get')
  2812. try:
  2813. return self.tk.getint(value)
  2814. except (ValueError, TypeError, TclError):
  2815. return self.tk.getdouble(value)
  2816. def set(self, value):
  2817. """Set the value to VALUE."""
  2818. self.tk.call(self._w, 'set', value)
  2819. def coords(self, value=None):
  2820. """Return a tuple (X,Y) of the point along the centerline of the
  2821. trough that corresponds to VALUE or the current value if None is
  2822. given."""
  2823. return self._getints(self.tk.call(self._w, 'coords', value))
  2824. def identify(self, x, y):
  2825. """Return where the point X,Y lies. Valid return values are "slider",
  2826. "though1" and "though2"."""
  2827. return self.tk.call(self._w, 'identify', x, y)
  2828. class Scrollbar(Widget):
  2829. """Scrollbar widget which displays a slider at a certain position."""
  2830. def __init__(self, master=None, cnf={}, **kw):
  2831. """Construct a scrollbar widget with the parent MASTER.
  2832. Valid resource names: activebackground, activerelief,
  2833. background, bd, bg, borderwidth, command, cursor,
  2834. elementborderwidth, highlightbackground,
  2835. highlightcolor, highlightthickness, jump, orient,
  2836. relief, repeatdelay, repeatinterval, takefocus,
  2837. troughcolor, width."""
  2838. Widget.__init__(self, master, 'scrollbar', cnf, kw)
  2839. def activate(self, index=None):
  2840. """Marks the element indicated by index as active.
  2841. The only index values understood by this method are "arrow1",
  2842. "slider", or "arrow2". If any other value is specified then no
  2843. element of the scrollbar will be active. If index is not specified,
  2844. the method returns the name of the element that is currently active,
  2845. or None if no element is active."""
  2846. return self.tk.call(self._w, 'activate', index) or None
  2847. def delta(self, deltax, deltay):
  2848. """Return the fractional change of the scrollbar setting if it
  2849. would be moved by DELTAX or DELTAY pixels."""
  2850. return self.tk.getdouble(
  2851. self.tk.call(self._w, 'delta', deltax, deltay))
  2852. def fraction(self, x, y):
  2853. """Return the fractional value which corresponds to a slider
  2854. position of X,Y."""
  2855. return self.tk.getdouble(self.tk.call(self._w, 'fraction', x, y))
  2856. def identify(self, x, y):
  2857. """Return the element under position X,Y as one of
  2858. "arrow1","slider","arrow2" or ""."""
  2859. return self.tk.call(self._w, 'identify', x, y)
  2860. def get(self):
  2861. """Return the current fractional values (upper and lower end)
  2862. of the slider position."""
  2863. return self._getdoubles(self.tk.call(self._w, 'get'))
  2864. def set(self, first, last):
  2865. """Set the fractional values of the slider position (upper and
  2866. lower ends as value between 0 and 1)."""
  2867. self.tk.call(self._w, 'set', first, last)
  2868. class Text(Widget, XView, YView):
  2869. """Text widget which can display text in various forms."""
  2870. def __init__(self, master=None, cnf={}, **kw):
  2871. """Construct a text widget with the parent MASTER.
  2872. STANDARD OPTIONS
  2873. background, borderwidth, cursor,
  2874. exportselection, font, foreground,
  2875. highlightbackground, highlightcolor,
  2876. highlightthickness, insertbackground,
  2877. insertborderwidth, insertofftime,
  2878. insertontime, insertwidth, padx, pady,
  2879. relief, selectbackground,
  2880. selectborderwidth, selectforeground,
  2881. setgrid, takefocus,
  2882. xscrollcommand, yscrollcommand,
  2883. WIDGET-SPECIFIC OPTIONS
  2884. autoseparators, height, maxundo,
  2885. spacing1, spacing2, spacing3,
  2886. state, tabs, undo, width, wrap,
  2887. """
  2888. Widget.__init__(self, master, 'text', cnf, kw)
  2889. def bbox(self, index):
  2890. """Return a tuple of (x,y,width,height) which gives the bounding
  2891. box of the visible part of the character at the given index."""
  2892. return self._getints(
  2893. self.tk.call(self._w, 'bbox', index)) or None
  2894. def compare(self, index1, op, index2):
  2895. """Return whether between index INDEX1 and index INDEX2 the
  2896. relation OP is satisfied. OP is one of <, <=, ==, >=, >, or !=."""
  2897. return self.tk.getboolean(self.tk.call(
  2898. self._w, 'compare', index1, op, index2))
  2899. def count(self, index1, index2, *args): # new in Tk 8.5
  2900. """Counts the number of relevant things between the two indices.
  2901. If index1 is after index2, the result will be a negative number
  2902. (and this holds for each of the possible options).
  2903. The actual items which are counted depends on the options given by
  2904. args. The result is a list of integers, one for the result of each
  2905. counting option given. Valid counting options are "chars",
  2906. "displaychars", "displayindices", "displaylines", "indices",
  2907. "lines", "xpixels" and "ypixels". There is an additional possible
  2908. option "update", which if given then all subsequent options ensure
  2909. that any possible out of date information is recalculated."""
  2910. args = ['-%s' % arg for arg in args if not arg.startswith('-')]
  2911. args += [index1, index2]
  2912. res = self.tk.call(self._w, 'count', *args) or None
  2913. if res is not None and len(args) <= 3:
  2914. return (res, )
  2915. else:
  2916. return res
  2917. def debug(self, boolean=None):
  2918. """Turn on the internal consistency checks of the B-Tree inside the text
  2919. widget according to BOOLEAN."""
  2920. if boolean is None:
  2921. return self.tk.getboolean(self.tk.call(self._w, 'debug'))
  2922. self.tk.call(self._w, 'debug', boolean)
  2923. def delete(self, index1, index2=None):
  2924. """Delete the characters between INDEX1 and INDEX2 (not included)."""
  2925. self.tk.call(self._w, 'delete', index1, index2)
  2926. def dlineinfo(self, index):
  2927. """Return tuple (x,y,width,height,baseline) giving the bounding box
  2928. and baseline position of the visible part of the line containing
  2929. the character at INDEX."""
  2930. return self._getints(self.tk.call(self._w, 'dlineinfo', index))
  2931. def dump(self, index1, index2=None, command=None, **kw):
  2932. """Return the contents of the widget between index1 and index2.
  2933. The type of contents returned in filtered based on the keyword
  2934. parameters; if 'all', 'image', 'mark', 'tag', 'text', or 'window' are
  2935. given and true, then the corresponding items are returned. The result
  2936. is a list of triples of the form (key, value, index). If none of the
  2937. keywords are true then 'all' is used by default.
  2938. If the 'command' argument is given, it is called once for each element
  2939. of the list of triples, with the values of each triple serving as the
  2940. arguments to the function. In this case the list is not returned."""
  2941. args = []
  2942. func_name = None
  2943. result = None
  2944. if not command:
  2945. # Never call the dump command without the -command flag, since the
  2946. # output could involve Tcl quoting and would be a pain to parse
  2947. # right. Instead just set the command to build a list of triples
  2948. # as if we had done the parsing.
  2949. result = []
  2950. def append_triple(key, value, index, result=result):
  2951. result.append((key, value, index))
  2952. command = append_triple
  2953. try:
  2954. if not isinstance(command, str):
  2955. func_name = command = self._register(command)
  2956. args += ["-command", command]
  2957. for key in kw:
  2958. if kw[key]: args.append("-" + key)
  2959. args.append(index1)
  2960. if index2:
  2961. args.append(index2)
  2962. self.tk.call(self._w, "dump", *args)
  2963. return result
  2964. finally:
  2965. if func_name:
  2966. self.deletecommand(func_name)
  2967. ## new in tk8.4
  2968. def edit(self, *args):
  2969. """Internal method
  2970. This method controls the undo mechanism and
  2971. the modified flag. The exact behavior of the
  2972. command depends on the option argument that
  2973. follows the edit argument. The following forms
  2974. of the command are currently supported:
  2975. edit_modified, edit_redo, edit_reset, edit_separator
  2976. and edit_undo
  2977. """
  2978. return self.tk.call(self._w, 'edit', *args)
  2979. def edit_modified(self, arg=None):
  2980. """Get or Set the modified flag
  2981. If arg is not specified, returns the modified
  2982. flag of the widget. The insert, delete, edit undo and
  2983. edit redo commands or the user can set or clear the
  2984. modified flag. If boolean is specified, sets the
  2985. modified flag of the widget to arg.
  2986. """
  2987. return self.edit("modified", arg)
  2988. def edit_redo(self):
  2989. """Redo the last undone edit
  2990. When the undo option is true, reapplies the last
  2991. undone edits provided no other edits were done since
  2992. then. Generates an error when the redo stack is empty.
  2993. Does nothing when the undo option is false.
  2994. """
  2995. return self.edit("redo")
  2996. def edit_reset(self):
  2997. """Clears the undo and redo stacks
  2998. """
  2999. return self.edit("reset")
  3000. def edit_separator(self):
  3001. """Inserts a separator (boundary) on the undo stack.
  3002. Does nothing when the undo option is false
  3003. """
  3004. return self.edit("separator")
  3005. def edit_undo(self):
  3006. """Undoes the last edit action
  3007. If the undo option is true. An edit action is defined
  3008. as all the insert and delete commands that are recorded
  3009. on the undo stack in between two separators. Generates
  3010. an error when the undo stack is empty. Does nothing
  3011. when the undo option is false
  3012. """
  3013. return self.edit("undo")
  3014. def get(self, index1, index2=None):
  3015. """Return the text from INDEX1 to INDEX2 (not included)."""
  3016. return self.tk.call(self._w, 'get', index1, index2)
  3017. # (Image commands are new in 8.0)
  3018. def image_cget(self, index, option):
  3019. """Return the value of OPTION of an embedded image at INDEX."""
  3020. if option[:1] != "-":
  3021. option = "-" + option
  3022. if option[-1:] == "_":
  3023. option = option[:-1]
  3024. return self.tk.call(self._w, "image", "cget", index, option)
  3025. def image_configure(self, index, cnf=None, **kw):
  3026. """Configure an embedded image at INDEX."""
  3027. return self._configure(('image', 'configure', index), cnf, kw)
  3028. def image_create(self, index, cnf={}, **kw):
  3029. """Create an embedded image at INDEX."""
  3030. return self.tk.call(
  3031. self._w, "image", "create", index,
  3032. *self._options(cnf, kw))
  3033. def image_names(self):
  3034. """Return all names of embedded images in this widget."""
  3035. return self.tk.call(self._w, "image", "names")
  3036. def index(self, index):
  3037. """Return the index in the form line.char for INDEX."""
  3038. return str(self.tk.call(self._w, 'index', index))
  3039. def insert(self, index, chars, *args):
  3040. """Insert CHARS before the characters at INDEX. An additional
  3041. tag can be given in ARGS. Additional CHARS and tags can follow in ARGS."""
  3042. self.tk.call((self._w, 'insert', index, chars) + args)
  3043. def mark_gravity(self, markName, direction=None):
  3044. """Change the gravity of a mark MARKNAME to DIRECTION (LEFT or RIGHT).
  3045. Return the current value if None is given for DIRECTION."""
  3046. return self.tk.call(
  3047. (self._w, 'mark', 'gravity', markName, direction))
  3048. def mark_names(self):
  3049. """Return all mark names."""
  3050. return self.tk.splitlist(self.tk.call(
  3051. self._w, 'mark', 'names'))
  3052. def mark_set(self, markName, index):
  3053. """Set mark MARKNAME before the character at INDEX."""
  3054. self.tk.call(self._w, 'mark', 'set', markName, index)
  3055. def mark_unset(self, *markNames):
  3056. """Delete all marks in MARKNAMES."""
  3057. self.tk.call((self._w, 'mark', 'unset') + markNames)
  3058. def mark_next(self, index):
  3059. """Return the name of the next mark after INDEX."""
  3060. return self.tk.call(self._w, 'mark', 'next', index) or None
  3061. def mark_previous(self, index):
  3062. """Return the name of the previous mark before INDEX."""
  3063. return self.tk.call(self._w, 'mark', 'previous', index) or None
  3064. def peer_create(self, newPathName, cnf={}, **kw): # new in Tk 8.5
  3065. """Creates a peer text widget with the given newPathName, and any
  3066. optional standard configuration options. By default the peer will
  3067. have the same start and end line as the parent widget, but
  3068. these can be overridden with the standard configuration options."""
  3069. self.tk.call(self._w, 'peer', 'create', newPathName,
  3070. *self._options(cnf, kw))
  3071. def peer_names(self): # new in Tk 8.5
  3072. """Returns a list of peers of this widget (this does not include
  3073. the widget itself)."""
  3074. return self.tk.splitlist(self.tk.call(self._w, 'peer', 'names'))
  3075. def replace(self, index1, index2, chars, *args): # new in Tk 8.5
  3076. """Replaces the range of characters between index1 and index2 with
  3077. the given characters and tags specified by args.
  3078. See the method insert for some more information about args, and the
  3079. method delete for information about the indices."""
  3080. self.tk.call(self._w, 'replace', index1, index2, chars, *args)
  3081. def scan_mark(self, x, y):
  3082. """Remember the current X, Y coordinates."""
  3083. self.tk.call(self._w, 'scan', 'mark', x, y)
  3084. def scan_dragto(self, x, y):
  3085. """Adjust the view of the text to 10 times the
  3086. difference between X and Y and the coordinates given in
  3087. scan_mark."""
  3088. self.tk.call(self._w, 'scan', 'dragto', x, y)
  3089. def search(self, pattern, index, stopindex=None,
  3090. forwards=None, backwards=None, exact=None,
  3091. regexp=None, nocase=None, count=None, elide=None):
  3092. """Search PATTERN beginning from INDEX until STOPINDEX.
  3093. Return the index of the first character of a match or an
  3094. empty string."""
  3095. args = [self._w, 'search']
  3096. if forwards: args.append('-forwards')
  3097. if backwards: args.append('-backwards')
  3098. if exact: args.append('-exact')
  3099. if regexp: args.append('-regexp')
  3100. if nocase: args.append('-nocase')
  3101. if elide: args.append('-elide')
  3102. if count: args.append('-count'); args.append(count)
  3103. if pattern and pattern[0] == '-': args.append('--')
  3104. args.append(pattern)
  3105. args.append(index)
  3106. if stopindex: args.append(stopindex)
  3107. return str(self.tk.call(tuple(args)))
  3108. def see(self, index):
  3109. """Scroll such that the character at INDEX is visible."""
  3110. self.tk.call(self._w, 'see', index)
  3111. def tag_add(self, tagName, index1, *args):
  3112. """Add tag TAGNAME to all characters between INDEX1 and index2 in ARGS.
  3113. Additional pairs of indices may follow in ARGS."""
  3114. self.tk.call(
  3115. (self._w, 'tag', 'add', tagName, index1) + args)
  3116. def tag_unbind(self, tagName, sequence, funcid=None):
  3117. """Unbind for all characters with TAGNAME for event SEQUENCE the
  3118. function identified with FUNCID."""
  3119. self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '')
  3120. if funcid:
  3121. self.deletecommand(funcid)
  3122. def tag_bind(self, tagName, sequence, func, add=None):
  3123. """Bind to all characters with TAGNAME at event SEQUENCE a call to function FUNC.
  3124. An additional boolean parameter ADD specifies whether FUNC will be
  3125. called additionally to the other bound function or whether it will
  3126. replace the previous function. See bind for the return value."""
  3127. return self._bind((self._w, 'tag', 'bind', tagName),
  3128. sequence, func, add)
  3129. def tag_cget(self, tagName, option):
  3130. """Return the value of OPTION for tag TAGNAME."""
  3131. if option[:1] != '-':
  3132. option = '-' + option
  3133. if option[-1:] == '_':
  3134. option = option[:-1]
  3135. return self.tk.call(self._w, 'tag', 'cget', tagName, option)
  3136. def tag_configure(self, tagName, cnf=None, **kw):
  3137. """Configure a tag TAGNAME."""
  3138. return self._configure(('tag', 'configure', tagName), cnf, kw)
  3139. tag_config = tag_configure
  3140. def tag_delete(self, *tagNames):
  3141. """Delete all tags in TAGNAMES."""
  3142. self.tk.call((self._w, 'tag', 'delete') + tagNames)
  3143. def tag_lower(self, tagName, belowThis=None):
  3144. """Change the priority of tag TAGNAME such that it is lower
  3145. than the priority of BELOWTHIS."""
  3146. self.tk.call(self._w, 'tag', 'lower', tagName, belowThis)
  3147. def tag_names(self, index=None):
  3148. """Return a list of all tag names."""
  3149. return self.tk.splitlist(
  3150. self.tk.call(self._w, 'tag', 'names', index))
  3151. def tag_nextrange(self, tagName, index1, index2=None):
  3152. """Return a list of start and end index for the first sequence of
  3153. characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3154. The text is searched forward from INDEX1."""
  3155. return self.tk.splitlist(self.tk.call(
  3156. self._w, 'tag', 'nextrange', tagName, index1, index2))
  3157. def tag_prevrange(self, tagName, index1, index2=None):
  3158. """Return a list of start and end index for the first sequence of
  3159. characters between INDEX1 and INDEX2 which all have tag TAGNAME.
  3160. The text is searched backwards from INDEX1."""
  3161. return self.tk.splitlist(self.tk.call(
  3162. self._w, 'tag', 'prevrange', tagName, index1, index2))
  3163. def tag_raise(self, tagName, aboveThis=None):
  3164. """Change the priority of tag TAGNAME such that it is higher
  3165. than the priority of ABOVETHIS."""
  3166. self.tk.call(
  3167. self._w, 'tag', 'raise', tagName, aboveThis)
  3168. def tag_ranges(self, tagName):
  3169. """Return a list of ranges of text which have tag TAGNAME."""
  3170. return self.tk.splitlist(self.tk.call(
  3171. self._w, 'tag', 'ranges', tagName))
  3172. def tag_remove(self, tagName, index1, index2=None):
  3173. """Remove tag TAGNAME from all characters between INDEX1 and INDEX2."""
  3174. self.tk.call(
  3175. self._w, 'tag', 'remove', tagName, index1, index2)
  3176. def window_cget(self, index, option):
  3177. """Return the value of OPTION of an embedded window at INDEX."""
  3178. if option[:1] != '-':
  3179. option = '-' + option
  3180. if option[-1:] == '_':
  3181. option = option[:-1]
  3182. return self.tk.call(self._w, 'window', 'cget', index, option)
  3183. def window_configure(self, index, cnf=None, **kw):
  3184. """Configure an embedded window at INDEX."""
  3185. return self._configure(('window', 'configure', index), cnf, kw)
  3186. window_config = window_configure
  3187. def window_create(self, index, cnf={}, **kw):
  3188. """Create a window at INDEX."""
  3189. self.tk.call(
  3190. (self._w, 'window', 'create', index)
  3191. + self._options(cnf, kw))
  3192. def window_names(self):
  3193. """Return all names of embedded windows in this widget."""
  3194. return self.tk.splitlist(
  3195. self.tk.call(self._w, 'window', 'names'))
  3196. def yview_pickplace(self, *what):
  3197. """Obsolete function, use see."""
  3198. self.tk.call((self._w, 'yview', '-pickplace') + what)
  3199. class _setit:
  3200. """Internal class. It wraps the command in the widget OptionMenu."""
  3201. def __init__(self, var, value, callback=None):
  3202. self.__value = value
  3203. self.__var = var
  3204. self.__callback = callback
  3205. def __call__(self, *args):
  3206. self.__var.set(self.__value)
  3207. if self.__callback is not None:
  3208. self.__callback(self.__value, *args)
  3209. class OptionMenu(Menubutton):
  3210. """OptionMenu which allows the user to select a value from a menu."""
  3211. def __init__(self, master, variable, value, *values, **kwargs):
  3212. """Construct an optionmenu widget with the parent MASTER, with
  3213. the resource textvariable set to VARIABLE, the initially selected
  3214. value VALUE, the other menu values VALUES and an additional
  3215. keyword argument command."""
  3216. kw = {"borderwidth": 2, "textvariable": variable,
  3217. "indicatoron": 1, "relief": RAISED, "anchor": "c",
  3218. "highlightthickness": 2}
  3219. Widget.__init__(self, master, "menubutton", kw)
  3220. self.widgetName = 'tk_optionMenu'
  3221. menu = self.__menu = Menu(self, name="menu", tearoff=0)
  3222. self.menuname = menu._w
  3223. # 'command' is the only supported keyword
  3224. callback = kwargs.get('command')
  3225. if 'command' in kwargs:
  3226. del kwargs['command']
  3227. if kwargs:
  3228. raise TclError('unknown option -'+next(iter(kwargs)))
  3229. menu.add_command(label=value,
  3230. command=_setit(variable, value, callback))
  3231. for v in values:
  3232. menu.add_command(label=v,
  3233. command=_setit(variable, v, callback))
  3234. self["menu"] = menu
  3235. def __getitem__(self, name):
  3236. if name == 'menu':
  3237. return self.__menu
  3238. return Widget.__getitem__(self, name)
  3239. def destroy(self):
  3240. """Destroy this widget and the associated menu."""
  3241. Menubutton.destroy(self)
  3242. self.__menu = None
  3243. class Image:
  3244. """Base class for images."""
  3245. _last_id = 0
  3246. def __init__(self, imgtype, name=None, cnf={}, master=None, **kw):
  3247. self.name = None
  3248. if master is None:
  3249. master = _get_default_root('create image')
  3250. self.tk = getattr(master, 'tk', master)
  3251. if not name:
  3252. Image._last_id += 1
  3253. name = "pyimage%r" % (Image._last_id,) # tk itself would use image<x>
  3254. if kw and cnf: cnf = _cnfmerge((cnf, kw))
  3255. elif kw: cnf = kw
  3256. options = ()
  3257. for k, v in cnf.items():
  3258. if callable(v):
  3259. v = self._register(v)
  3260. options = options + ('-'+k, v)
  3261. self.tk.call(('image', 'create', imgtype, name,) + options)
  3262. self.name = name
  3263. def __str__(self): return self.name
  3264. def __del__(self):
  3265. if self.name:
  3266. try:
  3267. self.tk.call('image', 'delete', self.name)
  3268. except TclError:
  3269. # May happen if the root was destroyed
  3270. pass
  3271. def __setitem__(self, key, value):
  3272. self.tk.call(self.name, 'configure', '-'+key, value)
  3273. def __getitem__(self, key):
  3274. return self.tk.call(self.name, 'configure', '-'+key)
  3275. def configure(self, **kw):
  3276. """Configure the image."""
  3277. res = ()
  3278. for k, v in _cnfmerge(kw).items():
  3279. if v is not None:
  3280. if k[-1] == '_': k = k[:-1]
  3281. if callable(v):
  3282. v = self._register(v)
  3283. res = res + ('-'+k, v)
  3284. self.tk.call((self.name, 'config') + res)
  3285. config = configure
  3286. def height(self):
  3287. """Return the height of the image."""
  3288. return self.tk.getint(
  3289. self.tk.call('image', 'height', self.name))
  3290. def type(self):
  3291. """Return the type of the image, e.g. "photo" or "bitmap"."""
  3292. return self.tk.call('image', 'type', self.name)
  3293. def width(self):
  3294. """Return the width of the image."""
  3295. return self.tk.getint(
  3296. self.tk.call('image', 'width', self.name))
  3297. class PhotoImage(Image):
  3298. """Widget which can display images in PGM, PPM, GIF, PNG format."""
  3299. def __init__(self, name=None, cnf={}, master=None, **kw):
  3300. """Create an image with NAME.
  3301. Valid resource names: data, format, file, gamma, height, palette,
  3302. width."""
  3303. Image.__init__(self, 'photo', name, cnf, master, **kw)
  3304. def blank(self):
  3305. """Display a transparent image."""
  3306. self.tk.call(self.name, 'blank')
  3307. def cget(self, option):
  3308. """Return the value of OPTION."""
  3309. return self.tk.call(self.name, 'cget', '-' + option)
  3310. # XXX config
  3311. def __getitem__(self, key):
  3312. return self.tk.call(self.name, 'cget', '-' + key)
  3313. # XXX copy -from, -to, ...?
  3314. def copy(self):
  3315. """Return a new PhotoImage with the same image as this widget."""
  3316. destImage = PhotoImage(master=self.tk)
  3317. self.tk.call(destImage, 'copy', self.name)
  3318. return destImage
  3319. def zoom(self, x, y=''):
  3320. """Return a new PhotoImage with the same image as this widget
  3321. but zoom it with a factor of x in the X direction and y in the Y
  3322. direction. If y is not given, the default value is the same as x.
  3323. """
  3324. destImage = PhotoImage(master=self.tk)
  3325. if y=='': y=x
  3326. self.tk.call(destImage, 'copy', self.name, '-zoom',x,y)
  3327. return destImage
  3328. def subsample(self, x, y=''):
  3329. """Return a new PhotoImage based on the same image as this widget
  3330. but use only every Xth or Yth pixel. If y is not given, the
  3331. default value is the same as x.
  3332. """
  3333. destImage = PhotoImage(master=self.tk)
  3334. if y=='': y=x
  3335. self.tk.call(destImage, 'copy', self.name, '-subsample',x,y)
  3336. return destImage
  3337. def get(self, x, y):
  3338. """Return the color (red, green, blue) of the pixel at X,Y."""
  3339. return self.tk.call(self.name, 'get', x, y)
  3340. def put(self, data, to=None):
  3341. """Put row formatted colors to image starting from
  3342. position TO, e.g. image.put("{red green} {blue yellow}", to=(4,6))"""
  3343. args = (self.name, 'put', data)
  3344. if to:
  3345. if to[0] == '-to':
  3346. to = to[1:]
  3347. args = args + ('-to',) + tuple(to)
  3348. self.tk.call(args)
  3349. # XXX read
  3350. def write(self, filename, format=None, from_coords=None):
  3351. """Write image to file FILENAME in FORMAT starting from
  3352. position FROM_COORDS."""
  3353. args = (self.name, 'write', filename)
  3354. if format:
  3355. args = args + ('-format', format)
  3356. if from_coords:
  3357. args = args + ('-from',) + tuple(from_coords)
  3358. self.tk.call(args)
  3359. def transparency_get(self, x, y):
  3360. """Return True if the pixel at x,y is transparent."""
  3361. return self.tk.getboolean(self.tk.call(
  3362. self.name, 'transparency', 'get', x, y))
  3363. def transparency_set(self, x, y, boolean):
  3364. """Set the transparency of the pixel at x,y."""
  3365. self.tk.call(self.name, 'transparency', 'set', x, y, boolean)
  3366. class BitmapImage(Image):
  3367. """Widget which can display images in XBM format."""
  3368. def __init__(self, name=None, cnf={}, master=None, **kw):
  3369. """Create a bitmap with NAME.
  3370. Valid resource names: background, data, file, foreground, maskdata, maskfile."""
  3371. Image.__init__(self, 'bitmap', name, cnf, master, **kw)
  3372. def image_names():
  3373. tk = _get_default_root('use image_names()').tk
  3374. return tk.splitlist(tk.call('image', 'names'))
  3375. def image_types():
  3376. tk = _get_default_root('use image_types()').tk
  3377. return tk.splitlist(tk.call('image', 'types'))
  3378. class Spinbox(Widget, XView):
  3379. """spinbox widget."""
  3380. def __init__(self, master=None, cnf={}, **kw):
  3381. """Construct a spinbox widget with the parent MASTER.
  3382. STANDARD OPTIONS
  3383. activebackground, background, borderwidth,
  3384. cursor, exportselection, font, foreground,
  3385. highlightbackground, highlightcolor,
  3386. highlightthickness, insertbackground,
  3387. insertborderwidth, insertofftime,
  3388. insertontime, insertwidth, justify, relief,
  3389. repeatdelay, repeatinterval,
  3390. selectbackground, selectborderwidth
  3391. selectforeground, takefocus, textvariable
  3392. xscrollcommand.
  3393. WIDGET-SPECIFIC OPTIONS
  3394. buttonbackground, buttoncursor,
  3395. buttondownrelief, buttonuprelief,
  3396. command, disabledbackground,
  3397. disabledforeground, format, from,
  3398. invalidcommand, increment,
  3399. readonlybackground, state, to,
  3400. validate, validatecommand values,
  3401. width, wrap,
  3402. """
  3403. Widget.__init__(self, master, 'spinbox', cnf, kw)
  3404. def bbox(self, index):
  3405. """Return a tuple of X1,Y1,X2,Y2 coordinates for a
  3406. rectangle which encloses the character given by index.
  3407. The first two elements of the list give the x and y
  3408. coordinates of the upper-left corner of the screen
  3409. area covered by the character (in pixels relative
  3410. to the widget) and the last two elements give the
  3411. width and height of the character, in pixels. The
  3412. bounding box may refer to a region outside the
  3413. visible area of the window.
  3414. """
  3415. return self._getints(self.tk.call(self._w, 'bbox', index)) or None
  3416. def delete(self, first, last=None):
  3417. """Delete one or more elements of the spinbox.
  3418. First is the index of the first character to delete,
  3419. and last is the index of the character just after
  3420. the last one to delete. If last isn't specified it
  3421. defaults to first+1, i.e. a single character is
  3422. deleted. This command returns an empty string.
  3423. """
  3424. return self.tk.call(self._w, 'delete', first, last)
  3425. def get(self):
  3426. """Returns the spinbox's string"""
  3427. return self.tk.call(self._w, 'get')
  3428. def icursor(self, index):
  3429. """Alter the position of the insertion cursor.
  3430. The insertion cursor will be displayed just before
  3431. the character given by index. Returns an empty string
  3432. """
  3433. return self.tk.call(self._w, 'icursor', index)
  3434. def identify(self, x, y):
  3435. """Returns the name of the widget at position x, y
  3436. Return value is one of: none, buttondown, buttonup, entry
  3437. """
  3438. return self.tk.call(self._w, 'identify', x, y)
  3439. def index(self, index):
  3440. """Returns the numerical index corresponding to index
  3441. """
  3442. return self.tk.call(self._w, 'index', index)
  3443. def insert(self, index, s):
  3444. """Insert string s at index
  3445. Returns an empty string.
  3446. """
  3447. return self.tk.call(self._w, 'insert', index, s)
  3448. def invoke(self, element):
  3449. """Causes the specified element to be invoked
  3450. The element could be buttondown or buttonup
  3451. triggering the action associated with it.
  3452. """
  3453. return self.tk.call(self._w, 'invoke', element)
  3454. def scan(self, *args):
  3455. """Internal function."""
  3456. return self._getints(
  3457. self.tk.call((self._w, 'scan') + args)) or ()
  3458. def scan_mark(self, x):
  3459. """Records x and the current view in the spinbox window;
  3460. used in conjunction with later scan dragto commands.
  3461. Typically this command is associated with a mouse button
  3462. press in the widget. It returns an empty string.
  3463. """
  3464. return self.scan("mark", x)
  3465. def scan_dragto(self, x):
  3466. """Compute the difference between the given x argument
  3467. and the x argument to the last scan mark command
  3468. It then adjusts the view left or right by 10 times the
  3469. difference in x-coordinates. This command is typically
  3470. associated with mouse motion events in the widget, to
  3471. produce the effect of dragging the spinbox at high speed
  3472. through the window. The return value is an empty string.
  3473. """
  3474. return self.scan("dragto", x)
  3475. def selection(self, *args):
  3476. """Internal function."""
  3477. return self._getints(
  3478. self.tk.call((self._w, 'selection') + args)) or ()
  3479. def selection_adjust(self, index):
  3480. """Locate the end of the selection nearest to the character
  3481. given by index,
  3482. Then adjust that end of the selection to be at index
  3483. (i.e including but not going beyond index). The other
  3484. end of the selection is made the anchor point for future
  3485. select to commands. If the selection isn't currently in
  3486. the spinbox, then a new selection is created to include
  3487. the characters between index and the most recent selection
  3488. anchor point, inclusive.
  3489. """
  3490. return self.selection("adjust", index)
  3491. def selection_clear(self):
  3492. """Clear the selection
  3493. If the selection isn't in this widget then the
  3494. command has no effect.
  3495. """
  3496. return self.selection("clear")
  3497. def selection_element(self, element=None):
  3498. """Sets or gets the currently selected element.
  3499. If a spinbutton element is specified, it will be
  3500. displayed depressed.
  3501. """
  3502. return self.tk.call(self._w, 'selection', 'element', element)
  3503. def selection_from(self, index):
  3504. """Set the fixed end of a selection to INDEX."""
  3505. self.selection('from', index)
  3506. def selection_present(self):
  3507. """Return True if there are characters selected in the spinbox, False
  3508. otherwise."""
  3509. return self.tk.getboolean(
  3510. self.tk.call(self._w, 'selection', 'present'))
  3511. def selection_range(self, start, end):
  3512. """Set the selection from START to END (not included)."""
  3513. self.selection('range', start, end)
  3514. def selection_to(self, index):
  3515. """Set the variable end of a selection to INDEX."""
  3516. self.selection('to', index)
  3517. ###########################################################################
  3518. class LabelFrame(Widget):
  3519. """labelframe widget."""
  3520. def __init__(self, master=None, cnf={}, **kw):
  3521. """Construct a labelframe widget with the parent MASTER.
  3522. STANDARD OPTIONS
  3523. borderwidth, cursor, font, foreground,
  3524. highlightbackground, highlightcolor,
  3525. highlightthickness, padx, pady, relief,
  3526. takefocus, text
  3527. WIDGET-SPECIFIC OPTIONS
  3528. background, class, colormap, container,
  3529. height, labelanchor, labelwidget,
  3530. visual, width
  3531. """
  3532. Widget.__init__(self, master, 'labelframe', cnf, kw)
  3533. ########################################################################
  3534. class PanedWindow(Widget):
  3535. """panedwindow widget."""
  3536. def __init__(self, master=None, cnf={}, **kw):
  3537. """Construct a panedwindow widget with the parent MASTER.
  3538. STANDARD OPTIONS
  3539. background, borderwidth, cursor, height,
  3540. orient, relief, width
  3541. WIDGET-SPECIFIC OPTIONS
  3542. handlepad, handlesize, opaqueresize,
  3543. sashcursor, sashpad, sashrelief,
  3544. sashwidth, showhandle,
  3545. """
  3546. Widget.__init__(self, master, 'panedwindow', cnf, kw)
  3547. def add(self, child, **kw):
  3548. """Add a child widget to the panedwindow in a new pane.
  3549. The child argument is the name of the child widget
  3550. followed by pairs of arguments that specify how to
  3551. manage the windows. The possible options and values
  3552. are the ones accepted by the paneconfigure method.
  3553. """
  3554. self.tk.call((self._w, 'add', child) + self._options(kw))
  3555. def remove(self, child):
  3556. """Remove the pane containing child from the panedwindow
  3557. All geometry management options for child will be forgotten.
  3558. """
  3559. self.tk.call(self._w, 'forget', child)
  3560. forget = remove
  3561. def identify(self, x, y):
  3562. """Identify the panedwindow component at point x, y
  3563. If the point is over a sash or a sash handle, the result
  3564. is a two element list containing the index of the sash or
  3565. handle, and a word indicating whether it is over a sash
  3566. or a handle, such as {0 sash} or {2 handle}. If the point
  3567. is over any other part of the panedwindow, the result is
  3568. an empty list.
  3569. """
  3570. return self.tk.call(self._w, 'identify', x, y)
  3571. def proxy(self, *args):
  3572. """Internal function."""
  3573. return self._getints(
  3574. self.tk.call((self._w, 'proxy') + args)) or ()
  3575. def proxy_coord(self):
  3576. """Return the x and y pair of the most recent proxy location
  3577. """
  3578. return self.proxy("coord")
  3579. def proxy_forget(self):
  3580. """Remove the proxy from the display.
  3581. """
  3582. return self.proxy("forget")
  3583. def proxy_place(self, x, y):
  3584. """Place the proxy at the given x and y coordinates.
  3585. """
  3586. return self.proxy("place", x, y)
  3587. def sash(self, *args):
  3588. """Internal function."""
  3589. return self._getints(
  3590. self.tk.call((self._w, 'sash') + args)) or ()
  3591. def sash_coord(self, index):
  3592. """Return the current x and y pair for the sash given by index.
  3593. Index must be an integer between 0 and 1 less than the
  3594. number of panes in the panedwindow. The coordinates given are
  3595. those of the top left corner of the region containing the sash.
  3596. pathName sash dragto index x y This command computes the
  3597. difference between the given coordinates and the coordinates
  3598. given to the last sash coord command for the given sash. It then
  3599. moves that sash the computed difference. The return value is the
  3600. empty string.
  3601. """
  3602. return self.sash("coord", index)
  3603. def sash_mark(self, index):
  3604. """Records x and y for the sash given by index;
  3605. Used in conjunction with later dragto commands to move the sash.
  3606. """
  3607. return self.sash("mark", index)
  3608. def sash_place(self, index, x, y):
  3609. """Place the sash given by index at the given coordinates
  3610. """
  3611. return self.sash("place", index, x, y)
  3612. def panecget(self, child, option):
  3613. """Query a management option for window.
  3614. Option may be any value allowed by the paneconfigure subcommand
  3615. """
  3616. return self.tk.call(
  3617. (self._w, 'panecget') + (child, '-'+option))
  3618. def paneconfigure(self, tagOrId, cnf=None, **kw):
  3619. """Query or modify the management options for window.
  3620. If no option is specified, returns a list describing all
  3621. of the available options for pathName. If option is
  3622. specified with no value, then the command returns a list
  3623. describing the one named option (this list will be identical
  3624. to the corresponding sublist of the value returned if no
  3625. option is specified). If one or more option-value pairs are
  3626. specified, then the command modifies the given widget
  3627. option(s) to have the given value(s); in this case the
  3628. command returns an empty string. The following options
  3629. are supported:
  3630. after window
  3631. Insert the window after the window specified. window
  3632. should be the name of a window already managed by pathName.
  3633. before window
  3634. Insert the window before the window specified. window
  3635. should be the name of a window already managed by pathName.
  3636. height size
  3637. Specify a height for the window. The height will be the
  3638. outer dimension of the window including its border, if
  3639. any. If size is an empty string, or if -height is not
  3640. specified, then the height requested internally by the
  3641. window will be used initially; the height may later be
  3642. adjusted by the movement of sashes in the panedwindow.
  3643. Size may be any value accepted by Tk_GetPixels.
  3644. minsize n
  3645. Specifies that the size of the window cannot be made
  3646. less than n. This constraint only affects the size of
  3647. the widget in the paned dimension -- the x dimension
  3648. for horizontal panedwindows, the y dimension for
  3649. vertical panedwindows. May be any value accepted by
  3650. Tk_GetPixels.
  3651. padx n
  3652. Specifies a non-negative value indicating how much
  3653. extra space to leave on each side of the window in
  3654. the X-direction. The value may have any of the forms
  3655. accepted by Tk_GetPixels.
  3656. pady n
  3657. Specifies a non-negative value indicating how much
  3658. extra space to leave on each side of the window in
  3659. the Y-direction. The value may have any of the forms
  3660. accepted by Tk_GetPixels.
  3661. sticky style
  3662. If a window's pane is larger than the requested
  3663. dimensions of the window, this option may be used
  3664. to position (or stretch) the window within its pane.
  3665. Style is a string that contains zero or more of the
  3666. characters n, s, e or w. The string can optionally
  3667. contains spaces or commas, but they are ignored. Each
  3668. letter refers to a side (north, south, east, or west)
  3669. that the window will "stick" to. If both n and s
  3670. (or e and w) are specified, the window will be
  3671. stretched to fill the entire height (or width) of
  3672. its cavity.
  3673. width size
  3674. Specify a width for the window. The width will be
  3675. the outer dimension of the window including its
  3676. border, if any. If size is an empty string, or
  3677. if -width is not specified, then the width requested
  3678. internally by the window will be used initially; the
  3679. width may later be adjusted by the movement of sashes
  3680. in the panedwindow. Size may be any value accepted by
  3681. Tk_GetPixels.
  3682. """
  3683. if cnf is None and not kw:
  3684. return self._getconfigure(self._w, 'paneconfigure', tagOrId)
  3685. if isinstance(cnf, str) and not kw:
  3686. return self._getconfigure1(
  3687. self._w, 'paneconfigure', tagOrId, '-'+cnf)
  3688. self.tk.call((self._w, 'paneconfigure', tagOrId) +
  3689. self._options(cnf, kw))
  3690. paneconfig = paneconfigure
  3691. def panes(self):
  3692. """Returns an ordered list of the child panes."""
  3693. return self.tk.splitlist(self.tk.call(self._w, 'panes'))
  3694. # Test:
  3695. def _test():
  3696. root = Tk()
  3697. text = "This is Tcl/Tk version %s" % TclVersion
  3698. text += "\nThis should be a cedilla: \xe7"
  3699. label = Label(root, text=text)
  3700. label.pack()
  3701. test = Button(root, text="Click me!",
  3702. command=lambda root=root: root.test.configure(
  3703. text="[%s]" % root.test['text']))
  3704. test.pack()
  3705. root.test = test
  3706. quit = Button(root, text="QUIT", command=root.destroy)
  3707. quit.pack()
  3708. # The following three commands are needed so the window pops
  3709. # up on top on Windows...
  3710. root.iconify()
  3711. root.update()
  3712. root.deiconify()
  3713. root.mainloop()
  3714. __all__ = [name for name, obj in globals().items()
  3715. if not name.startswith('_') and not isinstance(obj, types.ModuleType)
  3716. and name not in {'wantobjects'}]
  3717. if __name__ == '__main__':
  3718. _test()