Debian Codegraph @

07p/python/auto/graphics/Pmw.py

raw symbols SCIP
1
2 from auto.graphics import PmwColor as Color
3 from auto.graphics import PmwBlt as Blt
4
5 ### Loader functions:
6
7 _VERSION = '1.3'
8
9 def setversion(version):
10 if version != _VERSION:
11 raise ValueError('Dynamic versioning not available')
12
13 def setalphaversions(*alpha_versions):
14 if alpha_versions != ():
15 raise ValueError('Dynamic versioning not available')
16
17 def version(alpha = 0):
18 if alpha:
19 return ()
20 else:
21 return _VERSION
22
23 def installedversions(alpha = 0):
24 if alpha:
25 return ()
26 else:
27 return (_VERSION,)
28
29
30 ######################################################################
31 ### File: PmwBase.py
32 # Pmw megawidget base classes.
33
34 # This module provides a foundation for building megawidgets. It
35 # contains the MegaArchetype class which manages component widgets and
36 # configuration options. Also provided are the MegaToplevel and
37 # MegaWidget classes, derived from the MegaArchetype class. The
38 # MegaToplevel class contains a Tkinter Toplevel widget to act as the
39 # container of the megawidget. This is used as the base class of all
40 # megawidgets that are contained in their own top level window, such
41 # as a Dialog window. The MegaWidget class contains a Tkinter Frame
42 # to act as the container of the megawidget. This is used as the base
43 # class of all other megawidgets, such as a ComboBox or ButtonBox.
44 #
45 # Megawidgets are built by creating a class that inherits from either
46 # the MegaToplevel or MegaWidget class.
47
48 try:
49 long
50 except NameError:
51 long = int
52
53 import os
54 import sys
55 import traceback
56 try:
57 import Tkinter
58 except ImportError:
59 import tkinter as Tkinter # Python 3
60
61 # Special values used in index() methods of several megawidgets.
62 END = ['end']
63 SELECT = ['select']
64 DEFAULT = ['default']
65
66 # Constant used to indicate that an option can only be set by a call
67 # to the constructor.
68 INITOPT = ['initopt']
69 _DEFAULT_OPTION_VALUE = ['default_option_value']
70 _useTkOptionDb = 0
71
72 # Symbolic constants for the indexes into an optionInfo list.
73 _OPT_DEFAULT = 0
74 _OPT_VALUE = 1
75 _OPT_FUNCTION = 2
76
77 # Stacks
78
79 _busyStack = []
80 # Stack which tracks nested calls to show/hidebusycursor (called
81 # either directly or from activate()/deactivate()). Each element
82 # is a dictionary containing:
83 # 'newBusyWindows' : List of windows which had busy_hold called
84 # on them during a call to showbusycursor().
85 # The corresponding call to hidebusycursor()
86 # will call busy_release on these windows.
87 # 'busyFocus' : The blt _Busy window which showbusycursor()
88 # set the focus to.
89 # 'previousFocus' : The focus as it was when showbusycursor()
90 # was called. The corresponding call to
91 # hidebusycursor() will restore this focus if
92 # the focus has not been changed from busyFocus.
93
94 _grabStack = []
95 # Stack of grabbed windows. It tracks calls to push/popgrab()
96 # (called either directly or from activate()/deactivate()). The
97 # window on the top of the stack is the window currently with the
98 # grab. Each element is a dictionary containing:
99 # 'grabWindow' : The window grabbed by pushgrab(). The
100 # corresponding call to popgrab() will release
101 # the grab on this window and restore the grab
102 # on the next window in the stack (if there is one).
103 # 'globalMode' : True if the grabWindow was grabbed with a
104 # global grab, false if the grab was local
105 # and 'nograb' if no grab was performed.
106 # 'previousFocus' : The focus as it was when pushgrab()
107 # was called. The corresponding call to
108 # popgrab() will restore this focus.
109 # 'deactivateFunction' :
110 # The function to call (usually grabWindow.deactivate) if
111 # popgrab() is called (usually from a deactivate() method)
112 # on a window which is not at the top of the stack (that is,
113 # does not have the grab or focus). For example, if a modal
114 # dialog is deleted by the window manager or deactivated by
115 # a timer. In this case, all dialogs above and including
116 # this one are deactivated, starting at the top of the
117 # stack.
118
119 # Note that when dealing with focus windows, the name of the Tk
120 # widget is used, since it may be the '_Busy' window, which has no
121 # python instance associated with it.
122
123 #=============================================================================
124
125 # Functions used to forward methods from a class to a component.
126
127 # Fill in a flattened method resolution dictionary for a class (attributes are
128 # filtered out). Flattening honours the MI method resolution rules
129 # (depth-first search of bases in order). The dictionary has method names
130 # for keys and functions for values.
131 def __methodDict(cls, dict):
132
133 # the strategy is to traverse the class in the _reverse_ of the normal
134 # order, and overwrite any duplicates.
135 baseList = list(cls.__bases__)
136 baseList.reverse()
137
138 # do bases in reverse order, so first base overrides last base
139 for super in baseList:
140 __methodDict(super, dict)
141
142 # do my methods last to override base classes
143 for key, value in cls.__dict__.items():
144 # ignore class attributes
145 if isinstance(value, type(__methodDict)):
146 dict[key] = value
147
148 def __methods(cls):
149 # Return all method names for a class.
150
151 # Return all method names for a class (attributes are filtered
152 # out). Base classes are searched recursively.
153
154 dict = {}
155 __methodDict(cls, dict)
156 return dict.keys()
157
158 # Function body to resolve a forwarding given the target method name and the
159 # attribute name. The resulting lambda requires only self, but will forward
160 # any other parameters.
161 __stringBody = (
162 'def %(method)s(this, *args, **kw): return ' +
163 'this.%(attribute)s.%(method)s(*args, **kw)')
164
165 # Get a unique id
166 __counter = 0
167 def __unique():
168 global __counter
169 __counter = __counter + 1
170 return str(__counter)
171
172 # Function body to resolve a forwarding given the target method name and the
173 # index of the resolution function. The resulting lambda requires only self,
174 # but will forward any other parameters. The target instance is identified
175 # by invoking the resolution function.
176 __funcBody = (
177 'def %(method)s(this, *args, **kw): return ' +
178 'this.%(forwardFunc)s().%(method)s(*args, **kw)')
179
180 def forwardmethods(fromClass, toClass, toPart, exclude = ()):
181 # Forward all methods from one class to another.
182
183 # Forwarders will be created in fromClass to forward method
184 # invocations to toClass. The methods to be forwarded are
185 # identified by flattening the interface of toClass, and excluding
186 # methods identified in the exclude list. Methods already defined
187 # in fromClass, or special methods with one or more leading or
188 # trailing underscores will not be forwarded.
189
190 # For a given object of class fromClass, the corresponding toClass
191 # object is identified using toPart. This can either be a String
192 # denoting an attribute of fromClass objects, or a function taking
193 # a fromClass object and returning a toClass object.
194
195 # Example:
196 # class MyClass:
197 # ...
198 # def __init__(self):
199 # ...
200 # self.__target = TargetClass()
201 # ...
202 # def findtarget(self):
203 # return self.__target
204 # forwardmethods(MyClass, TargetClass, '__target', ['dangerous1', 'dangerous2'])
205 # # ...or...
206 # forwardmethods(MyClass, TargetClass, MyClass.findtarget,
207 # ['dangerous1', 'dangerous2'])
208
209 # In both cases, all TargetClass methods will be forwarded from
210 # MyClass except for dangerous1, dangerous2, special methods like
211 # __str__, and pre-existing methods like findtarget.
212
213
214 # Allow an attribute name (String) or a function to determine the instance
215 if not isinstance(toPart, str):
216
217 # check that it is something like a function
218 if hasattr(toPart, '__call__'):
219
220 # If a method is passed, use the function within it
221 if hasattr(toPart, 'im_func'):
222 toPart = toPart.im_func
223
224 # After this is set up, forwarders in this class will use
225 # the forwarding function. The forwarding function name is
226 # guaranteed to be unique, so that it can't be hidden by subclasses
227 forwardName = '__fwdfunc__' + __unique()
228 fromClass.__dict__[forwardName] = toPart
229
230 # It's not a valid type
231 else:
232 raise TypeError('toPart must be attribute name, function or method')
233
234 # get the full set of candidate methods
235 dict = {}
236 __methodDict(toClass, dict)
237
238 # discard special methods
239 for ex in list(dict):
240 if ex[:1] == '_' or ex[-1:] == '_':
241 del dict[ex]
242 # discard dangerous methods supplied by the caller
243 for ex in exclude:
244 if ex in dict:
245 del dict[ex]
246 # discard methods already defined in fromClass
247 for ex in __methods(fromClass):
248 if ex in dict:
249 del dict[ex]
250
251 for method, func in dict.items():
252 d = {'method': method, 'func': func}
253 if isinstance(toPart, str):
254 execString = \
255 __stringBody % {'method' : method, 'attribute' : toPart}
256 else:
257 execString = \
258 __funcBody % {'forwardFunc' : forwardName, 'method' : method}
259
260 exec(execString, d)
261
262 # this creates a method
263 setattr(fromClass, method, d[method])
264
265 #=============================================================================
266
267 def setgeometryanddeiconify(window, geom):
268 # To avoid flashes on X and to position the window correctly on NT
269 # (caused by Tk bugs).
270
271 if os.name == 'nt' or \
272 (os.name == 'posix' and sys.platform[:6] == 'cygwin'):
273 # Require overrideredirect trick to stop window frame
274 # appearing momentarily.
275 redirect = window.overrideredirect()
276 if not redirect:
277 window.overrideredirect(1)
278 window.deiconify()
279 if geom is not None:
280 window.geometry(geom)
281 # Call update_idletasks to ensure NT moves the window to the
282 # correct position it is raised.
283 window.update_idletasks()
284 window.tkraise()
285 if not redirect:
286 window.overrideredirect(0)
287 else:
288 if geom is not None:
289 window.geometry(geom)
290
291 # Problem!? Which way around should the following two calls
292 # go? If deiconify() is called first then I get complaints
293 # from people using the enlightenment or sawfish window
294 # managers that when a dialog is activated it takes about 2
295 # seconds for the contents of the window to appear. But if
296 # tkraise() is called first then I get complaints from people
297 # using the twm window manager that when a dialog is activated
298 # it appears in the top right corner of the screen and also
299 # takes about 2 seconds to appear.
300
301 #window.tkraise()
302 # Call update_idletasks to ensure certain window managers (eg:
303 # enlightenment and sawfish) do not cause Tk to delay for
304 # about two seconds before displaying window.
305 #window.update_idletasks()
306 #window.deiconify()
307
308 window.deiconify()
309 if window.overrideredirect():
310 # The window is not under the control of the window manager
311 # and so we need to raise it ourselves.
312 window.tkraise()
313
314 #=============================================================================
315
316 class MegaArchetype:
317 # Megawidget abstract root class.
318
319 # This class provides methods which are inherited by classes
320 # implementing useful bases (this class doesn't provide a
321 # container widget inside which the megawidget can be built).
322
323 def __init__(self, parent = None, hullClass = None):
324
325 # Mapping from each megawidget option to a list of information
326 # about the option
327 # - default value
328 # - current value
329 # - function to call when the option is initialised in the
330 # call to initialiseoptions() in the constructor or
331 # modified via configure(). If this is INITOPT, the
332 # option is an initialisation option (an option that can
333 # be set by the call to the constructor but can not be
334 # used with configure).
335 # This mapping is not initialised here, but in the call to
336 # defineoptions() which precedes construction of this base class.
337 #
338 # self._optionInfo = {}
339
340 # Mapping from each component name to a tuple of information
341 # about the component.
342 # - component widget instance
343 # - configure function of widget instance
344 # - the class of the widget (Frame, EntryField, etc)
345 # - cget function of widget instance
346 # - the name of the component group of this component, if any
347 self.__componentInfo = {}
348
349 # Mapping from alias names to the names of components or
350 # sub-components.
351 self.__componentAliases = {}
352
353 # Contains information about the keywords provided to the
354 # constructor. It is a mapping from the keyword to a tuple
355 # containing:
356 # - value of keyword
357 # - a boolean indicating if the keyword has been used.
358 # A keyword is used if, during the construction of a megawidget,
359 # - it is defined in a call to defineoptions() or addoptions(), or
360 # - it references, by name, a component of the megawidget, or
361 # - it references, by group, at least one component
362 # At the end of megawidget construction, a call is made to
363 # initialiseoptions() which reports an error if there are
364 # unused options given to the constructor.
365 #
366 # After megawidget construction, the dictionary contains
367 # keywords which refer to a dynamic component group, so that
368 # these components can be created after megawidget
369 # construction and still use the group options given to the
370 # constructor.
371 #
372 # self._constructorKeywords = {}
373
374 # List of dynamic component groups. If a group is included in
375 # this list, then it not an error if a keyword argument for
376 # the group is given to the constructor or to configure(), but
377 # no components with this group have been created.
378 # self._dynamicGroups = ()
379
380 if hullClass is None:
381 self._hull = None
382 else:
383 if parent is None:
384 parent = Tkinter._default_root
385
386 # Create the hull.
387 self._hull = self.createcomponent('hull',
388 (), None,
389 hullClass, (parent,))
390 _hullToMegaWidget[self._hull] = self
391
392 if _useTkOptionDb:
393 # Now that a widget has been created, query the Tk
394 # option database to get the default values for the
395 # options which have not been set in the call to the
396 # constructor. This assumes that defineoptions() is
397 # called before the __init__().
398 option_get = self.option_get
399 _VALUE = _OPT_VALUE
400 _DEFAULT = _OPT_DEFAULT
401 for name, info in self._optionInfo.items():
402 value = info[_VALUE]
403 if value is _DEFAULT_OPTION_VALUE:
404 resourceClass = name[0].upper() + name[1:]
405 value = option_get(name, resourceClass)
406 if value != '':
407 try:
408 # Convert the string to int/float/tuple, etc
409 value = eval(value, {'__builtins__': {}})
410 except:
411 pass
412 info[_VALUE] = value
413 else:
414 info[_VALUE] = info[_DEFAULT]
415
416 def destroy(self):
417 # Clean up optionInfo in case it contains circular references
418 # in the function field, such as self._settitle in class
419 # MegaToplevel.
420
421 self._optionInfo = {}
422 if self._hull is not None:
423 del _hullToMegaWidget[self._hull]
424 self._hull.destroy()
425
426 #======================================================================
427 # Methods used (mainly) during the construction of the megawidget.
428
429 def defineoptions(self, keywords, optionDefs, dynamicGroups = ()):
430 # Create options, providing the default value and the method
431 # to call when the value is changed. If any option created by
432 # base classes has the same name as one in <optionDefs>, the
433 # base class's value and function will be overriden.
434
435 # This should be called before the constructor of the base
436 # class, so that default values defined in the derived class
437 # override those in the base class.
438
439 if not hasattr(self, '_constructorKeywords'):
440 # First time defineoptions has been called.
441 tmp = {}
442 for option, value in keywords.items():
443 tmp[option] = [value, 0]
444 self._constructorKeywords = tmp
445 self._optionInfo = {}
446 self._initialiseoptions_counter = 0
447 self._initialiseoptions_counter = self._initialiseoptions_counter + 1
448
449 if not hasattr(self, '_dynamicGroups'):
450 self._dynamicGroups = ()
451 self._dynamicGroups = self._dynamicGroups + tuple(dynamicGroups)
452 self.addoptions(optionDefs)
453
454 def addoptions(self, optionDefs):
455 # Add additional options, providing the default value and the
456 # method to call when the value is changed. See
457 # "defineoptions" for more details
458
459 # optimisations:
460 optionInfo = self._optionInfo
461 optionInfo_has_key = optionInfo.__contains__
462 keywords = self._constructorKeywords
463 keywords_has_key = keywords.__contains__
464 FUNCTION = _OPT_FUNCTION
465
466 for name, default, function in optionDefs:
467 if '_' not in name:
468 # The option will already exist if it has been defined
469 # in a derived class. In this case, do not override the
470 # default value of the option or the callback function
471 # if it is not None.
472 if not optionInfo_has_key(name):
473 if keywords_has_key(name):
474 value = keywords[name][0]
475 optionInfo[name] = [default, value, function]
476 del keywords[name]
477 else:
478 if _useTkOptionDb:
479 optionInfo[name] = \
480 [default, _DEFAULT_OPTION_VALUE, function]
481 else:
482 optionInfo[name] = [default, default, function]
483 elif optionInfo[name][FUNCTION] is None:
484 optionInfo[name][FUNCTION] = function
485 else:
486 # This option is of the form "component_option". If this is
487 # not already defined in self._constructorKeywords add it.
488 # This allows a derived class to override the default value
489 # of an option of a component of a base class.
490 if not keywords_has_key(name):
491 keywords[name] = [default, 0]
492
493 def createcomponent(self, componentName, componentAliases,
494 componentGroup, widgetClass, *widgetArgs, **kw):
495 # Create a component (during construction or later).
496
497 if componentName in self.__componentInfo:
498 raise ValueError('Component "%s" already exists' % componentName)
499
500 if '_' in componentName:
501 raise ValueError('Component name "%s" must not contain "_"' % componentName)
502
503 if hasattr(self, '_constructorKeywords'):
504 keywords = self._constructorKeywords
505 else:
506 keywords = {}
507 for alias, component in componentAliases:
508 # Create aliases to the component and its sub-components.
509 index = component.find('_')
510 if index < 0:
511 self.__componentAliases[alias] = (component, None)
512 else:
513 mainComponent = component[:index]
514 subComponent = component[(index + 1):]
515 self.__componentAliases[alias] = (mainComponent, subComponent)
516
517 # Remove aliases from the constructor keyword arguments by
518 # replacing any keyword arguments that begin with *alias*
519 # with corresponding keys beginning with *component*.
520
521 alias = alias + '_'
522 aliasLen = len(alias)
523 for option in list(keywords):
524 if len(option) > aliasLen and option[:aliasLen] == alias:
525 newkey = component + '_' + option[aliasLen:]
526 keywords[newkey] = keywords[option]
527 del keywords[option]
528
529 componentPrefix = componentName + '_'
530 nameLen = len(componentPrefix)
531 for option in list(keywords):
532 if len(option) > nameLen and option[:nameLen] == componentPrefix:
533 # The keyword argument refers to this component, so add
534 # this to the options to use when constructing the widget.
535 kw[option[nameLen:]] = keywords[option][0]
536 del keywords[option]
537 else:
538 # Check if this keyword argument refers to the group
539 # of this component. If so, add this to the options
540 # to use when constructing the widget. Mark the
541 # keyword argument as being used, but do not remove it
542 # since it may be required when creating another
543 # component.
544 index = option.find('_')
545 if index >= 0 and componentGroup == option[:index]:
546 rest = option[(index + 1):]
547 kw[rest] = keywords[option][0]
548 keywords[option][1] = 1
549
550 if 'pyclass' in kw:
551 widgetClass = kw['pyclass']
552 del kw['pyclass']
553 if widgetClass is None:
554 return None
555 if len(widgetArgs) == 1 and isinstance(widgetArgs[0], tuple):
556 # Arguments to the constructor can be specified as either
557 # multiple trailing arguments to createcomponent() or as a
558 # single tuple argument.
559 widgetArgs = widgetArgs[0]
560 widget = widgetClass(*widgetArgs, **kw)
561 componentClass = widget.__class__.__name__
562 self.__componentInfo[componentName] = (widget, widget.configure,
563 componentClass, widget.cget, componentGroup)
564
565 return widget
566
567 def destroycomponent(self, name):
568 # Remove a megawidget component.
569
570 # This command is for use by megawidget designers to destroy a
571 # megawidget component.
572
573 self.__componentInfo[name][0].destroy()
574 del self.__componentInfo[name]
575
576 def createlabel(self, parent, childCols = 1, childRows = 1):
577
578 labelpos = self['labelpos']
579 labelmargin = self['labelmargin']
580 if labelpos is None:
581 return
582
583 label = self.createcomponent('label',
584 (), None,
585 Tkinter.Label, (parent,))
586
587 if labelpos[0] in 'ns':
588 # vertical layout
589 if labelpos[0] == 'n':
590 row = 0
591 margin = 1
592 else:
593 row = childRows + 3
594 margin = row - 1
595 label.grid(column=2, row=row, columnspan=childCols, sticky=labelpos)
596 parent.grid_rowconfigure(margin, minsize=labelmargin)
597 else:
598 # horizontal layout
599 if labelpos[0] == 'w':
600 col = 0
601 margin = 1
602 else:
603 col = childCols + 3
604 margin = col - 1
605 label.grid(column=col, row=2, rowspan=childRows, sticky=labelpos)
606 parent.grid_columnconfigure(margin, minsize=labelmargin)
607
608 def initialiseoptions(self, dummy = None):
609 self._initialiseoptions_counter = self._initialiseoptions_counter - 1
610 if self._initialiseoptions_counter == 0:
611 unusedOptions = []
612 keywords = self._constructorKeywords
613 for name in keywords:
614 used = keywords[name][1]
615 if not used:
616 # This keyword argument has not been used. If it
617 # does not refer to a dynamic group, mark it as
618 # unused.
619 index = name.find('_')
620 if index < 0 or name[:index] not in self._dynamicGroups:
621 unusedOptions.append(name)
622 if len(unusedOptions) > 0:
623 if len(unusedOptions) == 1:
624 text = 'Unknown option "'
625 else:
626 text = 'Unknown options "'
627 raise KeyError(text + ', '.join(unusedOptions) + \
628 '" for ' + self.__class__.__name__)
629
630 # Call the configuration callback function for every option.
631 FUNCTION = _OPT_FUNCTION
632 for info in self._optionInfo.values():
633 func = info[FUNCTION]
634 if func is not None and func is not INITOPT:
635 func()
636
637 #======================================================================
638 # Method used to configure the megawidget.
639
640 def configure(self, option=None, **kw):
641 # Query or configure the megawidget options.
642 #
643 # If not empty, *kw* is a dictionary giving new
644 # values for some of the options of this megawidget or its
645 # components. For options defined for this megawidget, set
646 # the value of the option to the new value and call the
647 # configuration callback function, if any. For options of the
648 # form <component>_<option>, where <component> is a component
649 # of this megawidget, call the configure method of the
650 # component giving it the new value of the option. The
651 # <component> part may be an alias or a component group name.
652 #
653 # If *option* is None, return all megawidget configuration
654 # options and settings. Options are returned as standard 5
655 # element tuples
656 #
657 # If *option* is a string, return the 5 element tuple for the
658 # given configuration option.
659
660 # First, deal with the option queries.
661 if len(kw) == 0:
662 # This configure call is querying the values of one or all options.
663 # Return 5-tuples:
664 # (optionName, resourceName, resourceClass, default, value)
665 if option is None:
666 rtn = {}
667 for option, config in self._optionInfo.items():
668 resourceClass = option[0].upper() + option[1:]
669 rtn[option] = (option, option, resourceClass,
670 config[_OPT_DEFAULT], config[_OPT_VALUE])
671 return rtn
672 else:
673 config = self._optionInfo[option]
674 resourceClass = option[0].upper() + option[1:]
675 return (option, option, resourceClass, config[_OPT_DEFAULT],
676 config[_OPT_VALUE])
677
678 # optimisations:
679 optionInfo = self._optionInfo
680 optionInfo_has_key = optionInfo.__contains__
681 componentInfo = self.__componentInfo
682 componentInfo_has_key = componentInfo.__contains__
683 componentAliases = self.__componentAliases
684 componentAliases_has_key = componentAliases.__contains__
685 VALUE = _OPT_VALUE
686 FUNCTION = _OPT_FUNCTION
687
688 # This will contain a list of options in *kw* which
689 # are known to this megawidget.
690 directOptions = []
691
692 # This will contain information about the options in
693 # *kw* of the form <component>_<option>, where
694 # <component> is a component of this megawidget. It is a
695 # dictionary whose keys are the configure method of each
696 # component and whose values are a dictionary of options and
697 # values for the component.
698 indirectOptions = {}
699 indirectOptions_has_key = indirectOptions.__contains__
700
701 for option, value in kw.items():
702 if optionInfo_has_key(option):
703 # This is one of the options of this megawidget.
704 # Make sure it is not an initialisation option.
705 if optionInfo[option][FUNCTION] is INITOPT:
706 raise KeyError('Cannot configure initialisation option "' \
707 + option + '" for ' + self.__class__.__name__)
708 optionInfo[option][VALUE] = value
709 directOptions.append(option)
710 else:
711 index = option.find('_')
712 if index >= 0:
713 # This option may be of the form <component>_<option>.
714 component = option[:index]
715 componentOption = option[(index + 1):]
716
717 # Expand component alias
718 if componentAliases_has_key(component):
719 component, subComponent = componentAliases[component]
720 if subComponent is not None:
721 componentOption = subComponent + '_' \
722 + componentOption
723
724 # Expand option string to write on error
725 option = component + '_' + componentOption
726
727 if componentInfo_has_key(component):
728 # Configure the named component
729 componentConfigFuncs = [componentInfo[component][1]]
730 else:
731 # Check if this is a group name and configure all
732 # components in the group.
733 componentConfigFuncs = []
734 for info in componentInfo.values():
735 if info[4] == component:
736 componentConfigFuncs.append(info[1])
737
738 if len(componentConfigFuncs) == 0 and \
739 component not in self._dynamicGroups:
740 raise KeyError('Unknown option "' + option + \
741 '" for ' + self.__class__.__name__)
742
743 # Add the configure method(s) (may be more than
744 # one if this is configuring a component group)
745 # and option/value to dictionary.
746 for componentConfigFunc in componentConfigFuncs:
747 if not indirectOptions_has_key(componentConfigFunc):
748 indirectOptions[componentConfigFunc] = {}
749 indirectOptions[componentConfigFunc][componentOption] \
750 = value
751 else:
752 raise KeyError('Unknown option "' + option + \
753 '" for ' + self.__class__.__name__)
754
755 # Call the configure methods for any components
756 for k in indirectOptions:
757 k(**indirectOptions[k])
758
759 # Call the configuration callback function for each option.
760 for option in directOptions:
761 info = optionInfo[option]
762 func = info[_OPT_FUNCTION]
763 if func is not None:
764 func()
765
766 def __setitem__(self, key, value):
767 self.configure(**{key:value})
768
769 #======================================================================
770 # Methods used to query the megawidget.
771
772 def component(self, name):
773 # Return a component widget of the megawidget given the
774 # component's name
775 # This allows the user of a megawidget to access and configure
776 # widget components directly.
777
778 # Find the main component and any subcomponents
779 index = name.find('_')
780 if index < 0:
781 component = name
782 remainingComponents = None
783 else:
784 component = name[:index]
785 remainingComponents = name[(index + 1):]
786
787 # Expand component alias
788 if component in self.__componentAliases:
789 component, subComponent = self.__componentAliases[component]
790 if subComponent is not None:
791 if remainingComponents is None:
792 remainingComponents = subComponent
793 else:
794 remainingComponents = subComponent + '_' \
795 + remainingComponents
796
797 widget = self.__componentInfo[component][0]
798 if remainingComponents is None:
799 return widget
800 else:
801 return widget.component(remainingComponents)
802
803 def interior(self):
804 return self._hull
805
806 def hulldestroyed(self):
807 return self._hull not in _hullToMegaWidget
808
809 def __str__(self):
810 return str(self._hull)
811
812 def cget(self, option):
813 # Get current configuration setting.
814
815 # Return the value of an option, for example myWidget['font'].
816
817 if option in self._optionInfo:
818 return self._optionInfo[option][_OPT_VALUE]
819 else:
820 index = option.find('_')
821 if index >= 0:
822 component = option[:index]
823 componentOption = option[(index + 1):]
824
825 # Expand component alias
826 if component in self.__componentAliases:
827 component, subComponent = self.__componentAliases[component]
828 if subComponent is not None:
829 componentOption = subComponent + '_' + componentOption
830
831 # Expand option string to write on error
832 option = component + '_' + componentOption
833
834 if component in self.__componentInfo:
835 # Call cget on the component.
836 componentCget = self.__componentInfo[component][3]
837 return componentCget(componentOption)
838 else:
839 # If this is a group name, call cget for one of
840 # the components in the group.
841 for info in self.__componentInfo.values():
842 if info[4] == component:
843 componentCget = info[3]
844 return componentCget(componentOption)
845
846 raise KeyError('Unknown option "' + option + \
847 '" for ' + self.__class__.__name__)
848
849 __getitem__ = cget
850
851 def isinitoption(self, option):
852 return self._optionInfo[option][_OPT_FUNCTION] is INITOPT
853
854 def options(self):
855 options = []
856 if hasattr(self, '_optionInfo'):
857 for option, info in self._optionInfo.items():
858 isinit = info[_OPT_FUNCTION] is INITOPT
859 default = info[_OPT_DEFAULT]
860 options.append((option, default, isinit))
861 options.sort()
862 return options
863
864 def components(self):
865 # Return a list of all components.
866
867 # This list includes the 'hull' component and all widget subcomponents
868
869 names = list(self.__componentInfo)
870 names.sort()
871 return names
872
873 def componentaliases(self):
874 # Return a list of all component aliases.
875
876 componentAliases = self.__componentAliases
877
878 names = list(componentAliases)
879 names.sort()
880 rtn = []
881 for alias in names:
882 (mainComponent, subComponent) = componentAliases[alias]
883 if subComponent is None:
884 rtn.append((alias, mainComponent))
885 else:
886 rtn.append((alias, mainComponent + '_' + subComponent))
887
888 return rtn
889
890 def componentgroup(self, name):
891 return self.__componentInfo[name][4]
892
893 #=============================================================================
894
895 # The grab functions are mainly called by the activate() and
896 # deactivate() methods.
897 #
898 # Use pushgrab() to add a new window to the grab stack. This
899 # releases the grab by the window currently on top of the stack (if
900 # there is one) and gives the grab and focus to the new widget.
901 #
902 # To remove the grab from the window on top of the grab stack, call
903 # popgrab().
904 #
905 # Use releasegrabs() to release the grab and clear the grab stack.
906
907 def pushgrab(grabWindow, globalMode, deactivateFunction):
908 prevFocus = grabWindow.tk.call('focus')
909 grabInfo = {
910 'grabWindow' : grabWindow,
911 'globalMode' : globalMode,
912 'previousFocus' : prevFocus,
913 'deactivateFunction' : deactivateFunction,
914 }
915 _grabStack.append(grabInfo)
916 _grabtop()
917 grabWindow.focus_set()
918
919 def popgrab(window):
920 # Return the grab to the next window in the grab stack, if any.
921
922 # If this window is not at the top of the grab stack, then it has
923 # just been deleted by the window manager or deactivated by a
924 # timer. Call the deactivate method for the modal dialog above
925 # this one on the stack.
926 if _grabStack[-1]['grabWindow'] != window:
927 for index in range(len(_grabStack)):
928 if _grabStack[index]['grabWindow'] == window:
929 _grabStack[index + 1]['deactivateFunction']()
930 break
931
932 grabInfo = _grabStack[-1]
933 del _grabStack[-1]
934
935 topWidget = grabInfo['grabWindow']
936 prevFocus = grabInfo['previousFocus']
937 globalMode = grabInfo['globalMode']
938
939 if globalMode != 'nograb':
940 topWidget.grab_release()
941
942 if len(_grabStack) > 0:
943 _grabtop()
944 if prevFocus != '':
945 try:
946 topWidget.tk.call('focus', prevFocus)
947 except Tkinter.TclError:
948 # Previous focus widget has been deleted. Set focus
949 # to root window.
950 Tkinter._default_root.focus_set()
951 else:
952 # Make sure that focus does not remain on the released widget.
953 if len(_grabStack) > 0:
954 topWidget = _grabStack[-1]['grabWindow']
955 topWidget.focus_set()
956 else:
957 Tkinter._default_root.focus_set()
958
959 def grabstacktopwindow():
960 if len(_grabStack) == 0:
961 return None
962 else:
963 return _grabStack[-1]['grabWindow']
964
965 def releasegrabs():
966 # Release grab and clear the grab stack.
967
968 current = Tkinter._default_root.grab_current()
969 if current is not None:
970 current.grab_release()
971 _grabStack[:] = []
972
973 def _grabtop():
974 grabInfo = _grabStack[-1]
975 topWidget = grabInfo['grabWindow']
976 globalMode = grabInfo['globalMode']
977
978 if globalMode == 'nograb':
979 return
980
981 while 1:
982 try:
983 if globalMode:
984 topWidget.grab_set_global()
985 else:
986 topWidget.grab_set()
987 break
988 except Tkinter.TclError:
989 # Another application has grab. Keep trying until
990 # grab can succeed.
991 topWidget.after(100)
992
993 #=============================================================================
994
995 class MegaToplevel(MegaArchetype):
996
997 def __init__(self, parent = None, **kw):
998 # Define the options for this megawidget.
999 optiondefs = (
1000 ('activatecommand', None, None),
1001 ('deactivatecommand', None, None),
1002 ('master', None, None),
1003 ('title', None, self._settitle),
1004 ('hull_class', self.__class__.__name__, None),
1005 )
1006 self.defineoptions(kw, optiondefs)
1007
1008 # Initialise the base class (after defining the options).
1009 MegaArchetype.__init__(self, parent, Tkinter.Toplevel)
1010
1011 # Initialise instance.
1012
1013 # Set WM_DELETE_WINDOW protocol, deleting any old callback, so
1014 # memory does not leak.
1015 if hasattr(self._hull, '_Pmw_WM_DELETE_name'):
1016 self._hull.tk.deletecommand(self._hull._Pmw_WM_DELETE_name)
1017 self._hull._Pmw_WM_DELETE_name = \
1018 self.register(self._userDeleteWindow, needcleanup = 0)
1019 self.protocol('WM_DELETE_WINDOW', self._hull._Pmw_WM_DELETE_name)
1020
1021 # Initialise instance variables.
1022
1023 self._firstShowing = 1
1024 # Used by show() to ensure window retains previous position on screen.
1025
1026 # The IntVar() variable to wait on during a modal dialog.
1027 self._wait = None
1028
1029 self._active = 0
1030 self._userDeleteFunc = self.destroy
1031 self._userModalDeleteFunc = self.deactivate
1032
1033 # Check keywords and initialise options.
1034 self.initialiseoptions()
1035
1036 def _settitle(self):
1037 title = self['title']
1038 if title is not None:
1039 self.title(title)
1040
1041 def userdeletefunc(self, func=None):
1042 if func:
1043 self._userDeleteFunc = func
1044 else:
1045 return self._userDeleteFunc
1046
1047 def usermodaldeletefunc(self, func=None):
1048 if func:
1049 self._userModalDeleteFunc = func
1050 else:
1051 return self._userModalDeleteFunc
1052
1053 def _userDeleteWindow(self):
1054 if self.active():
1055 self._userModalDeleteFunc()
1056 else:
1057 self._userDeleteFunc()
1058
1059 def destroy(self):
1060 # Allow this to be called more than once.
1061 if self._hull in _hullToMegaWidget:
1062 self.deactivate()
1063
1064 # Remove circular references, so that object can get cleaned up.
1065 del self._userDeleteFunc
1066 del self._userModalDeleteFunc
1067
1068 MegaArchetype.destroy(self)
1069
1070 def show(self, master = None):
1071 if self.state() != 'normal':
1072 if self._firstShowing:
1073 # Just let the window manager determine the window
1074 # position for the first time.
1075 geom = None
1076 else:
1077 # Position the window at the same place it was last time.
1078 geom = self._sameposition()
1079 setgeometryanddeiconify(self, geom)
1080
1081 if self._firstShowing:
1082 self._firstShowing = 0
1083 else:
1084 if self.transient() == '':
1085 self.tkraise()
1086
1087 # Do this last, otherwise get flashing on NT:
1088 if master is not None:
1089 if master == 'parent':
1090 parent = self.winfo_parent()
1091 # winfo_parent() should return the parent widget, but the
1092 # the current version of Tkinter returns a string.
1093 if isinstance(parent, str):
1094 parent = self._hull._nametowidget(parent)
1095 master = parent.winfo_toplevel()
1096 self.transient(master)
1097
1098 self.focus()
1099
1100 def _centreonscreen(self):
1101 # Centre the window on the screen. (Actually halfway across
1102 # and one third down.)
1103
1104 parent = self.winfo_parent()
1105 if isinstance(parent, str):
1106 parent = self._hull._nametowidget(parent)
1107
1108 # Find size of window.
1109 self.update_idletasks()
1110 width = self.winfo_width()
1111 height = self.winfo_height()
1112 if width == 1 and height == 1:
1113 # If the window has not yet been displayed, its size is
1114 # reported as 1x1, so use requested size.
1115 width = self.winfo_reqwidth()
1116 height = self.winfo_reqheight()
1117
1118 # Place in centre of screen:
1119 x = (self.winfo_screenwidth() - width) / 2 - parent.winfo_vrootx()
1120 y = (self.winfo_screenheight() - height) / 3 - parent.winfo_vrooty()
1121 if x < 0:
1122 x = 0
1123 if y < 0:
1124 y = 0
1125 return '+%d+%d' % (x, y)
1126
1127 def _sameposition(self):
1128 # Position the window at the same place it was last time.
1129
1130 geometry = self.geometry()
1131 index = geometry.find('+')
1132 if index >= 0:
1133 return geometry[index:]
1134 else:
1135 return None
1136
1137 def activate(self, globalMode = 0, geometry = 'centerscreenfirst'):
1138 if self._active:
1139 raise ValueError('Window is already active')
1140 if self.state() == 'normal':
1141 self.withdraw()
1142
1143 self._active = 1
1144
1145 showbusycursor()
1146
1147 if self._wait is None:
1148 self._wait = Tkinter.IntVar()
1149 self._wait.set(0)
1150
1151 if geometry == 'centerscreenalways':
1152 geom = self._centreonscreen()
1153 elif geometry == 'centerscreenfirst':
1154 if self._firstShowing:
1155 # Centre the window the first time it is displayed.
1156 geom = self._centreonscreen()
1157 else:
1158 # Position the window at the same place it was last time.
1159 geom = self._sameposition()
1160 elif geometry[:5] == 'first':
1161 if self._firstShowing:
1162 geom = geometry[5:]
1163 else:
1164 # Position the window at the same place it was last time.
1165 geom = self._sameposition()
1166 else:
1167 geom = geometry
1168
1169 self._firstShowing = 0
1170
1171 setgeometryanddeiconify(self, geom)
1172
1173 # Do this last, otherwise get flashing on NT:
1174 master = self['master']
1175 if master is not None:
1176 if master == 'parent':
1177 parent = self.winfo_parent()
1178 # winfo_parent() should return the parent widget, but the
1179 # the current version of Tkinter returns a string.
1180 if isinstance(parent, str):
1181 parent = self._hull._nametowidget(parent)
1182 master = parent.winfo_toplevel()
1183 self.transient(master)
1184
1185 pushgrab(self._hull, globalMode, self.deactivate)
1186 command = self['activatecommand']
1187 if hasattr(command, '__call__'):
1188 command()
1189 self.wait_variable(self._wait)
1190
1191 return self._result
1192
1193 def deactivate(self, result=None):
1194 if not self._active:
1195 return
1196 self._active = 0
1197
1198 # Restore the focus before withdrawing the window, since
1199 # otherwise the window manager may take the focus away so we
1200 # can't redirect it. Also, return the grab to the next active
1201 # window in the stack, if any.
1202 popgrab(self._hull)
1203
1204 command = self['deactivatecommand']
1205 if hasattr(command, '__call__'):
1206 command()
1207
1208 self.withdraw()
1209 hidebusycursor(forceFocusRestore = 1)
1210
1211 self._result = result
1212 self._wait.set(1)
1213
1214 def active(self):
1215 return self._active
1216
1217 forwardmethods(MegaToplevel, Tkinter.Toplevel, '_hull')
1218
1219 #=============================================================================
1220
1221 class MegaWidget(MegaArchetype):
1222 def __init__(self, parent = None, **kw):
1223 # Define the options for this megawidget.
1224 optiondefs = (
1225 ('hull_class', self.__class__.__name__, None),
1226 )
1227 self.defineoptions(kw, optiondefs)
1228
1229 # Initialise the base class (after defining the options).
1230 MegaArchetype.__init__(self, parent, Tkinter.Frame)
1231
1232 # Check keywords and initialise options.
1233 self.initialiseoptions()
1234
1235 forwardmethods(MegaWidget, Tkinter.Frame, '_hull')
1236
1237 #=============================================================================
1238
1239 # Public functions
1240 #-----------------
1241
1242 _traceTk = 0
1243 def tracetk(root = None, on = 1, withStackTrace = 0, file=None):
1244 global _withStackTrace
1245 global _traceTkFile
1246 global _traceTk
1247
1248 if root is None:
1249 root = Tkinter._default_root
1250
1251 _withStackTrace = withStackTrace
1252 _traceTk = on
1253 if on:
1254 if hasattr(root.tk, '__class__'):
1255 # Tracing already on
1256 return
1257 if file is None:
1258 _traceTkFile = sys.stderr
1259 else:
1260 _traceTkFile = file
1261 tk = _TraceTk(root.tk)
1262 else:
1263 if not hasattr(root.tk, '__class__'):
1264 # Tracing already off
1265 return
1266 tk = root.tk.getTclInterp()
1267 _setTkInterps(root, tk)
1268
1269 def showbusycursor():
1270
1271 _addRootToToplevelBusyInfo()
1272 root = Tkinter._default_root
1273
1274 busyInfo = {
1275 'newBusyWindows' : [],
1276 'previousFocus' : None,
1277 'busyFocus' : None,
1278 }
1279 _busyStack.append(busyInfo)
1280
1281 if _disableKeyboardWhileBusy:
1282 # Remember the focus as it is now, before it is changed.
1283 busyInfo['previousFocus'] = root.tk.call('focus')
1284
1285 if not _havebltbusy(root):
1286 # No busy command, so don't call busy hold on any windows.
1287 return
1288
1289 for (window, winInfo) in _toplevelBusyInfo.items():
1290 if (window.state() != 'withdrawn' and not winInfo['isBusy']
1291 and not winInfo['excludeFromBusy']):
1292 busyInfo['newBusyWindows'].append(window)
1293 winInfo['isBusy'] = 1
1294 _busy_hold(window, winInfo['busyCursorName'])
1295
1296 # Make sure that no events for the busy window get
1297 # through to Tkinter, otherwise it will crash in
1298 # _nametowidget with a 'KeyError: _Busy' if there is
1299 # a binding on the toplevel window.
1300 window.tk.call('bindtags', winInfo['busyWindow'], 'Pmw_Dummy_Tag')
1301
1302 if _disableKeyboardWhileBusy:
1303 # Remember previous focus widget for this toplevel window
1304 # and set focus to the busy window, which will ignore all
1305 # keyboard events.
1306 winInfo['windowFocus'] = \
1307 window.tk.call('focus', '-lastfor', window._w)
1308 window.tk.call('focus', winInfo['busyWindow'])
1309 busyInfo['busyFocus'] = winInfo['busyWindow']
1310
1311 if len(busyInfo['newBusyWindows']) > 0:
1312 if os.name == 'nt':
1313 # NT needs an "update" before it will change the cursor.
1314 window.update()
1315 else:
1316 window.update_idletasks()
1317
1318 def hidebusycursor(forceFocusRestore = 0):
1319
1320 # Remember the focus as it is now, before it is changed.
1321 root = Tkinter._default_root
1322 if _disableKeyboardWhileBusy:
1323 currentFocus = root.tk.call('focus')
1324
1325 # Pop the busy info off the stack.
1326 busyInfo = _busyStack[-1]
1327 del _busyStack[-1]
1328
1329 for window in busyInfo['newBusyWindows']:
1330 # If this window has not been deleted, release the busy cursor.
1331 if window in _toplevelBusyInfo:
1332 winInfo = _toplevelBusyInfo[window]
1333 winInfo['isBusy'] = 0
1334 _busy_release(window)
1335
1336 if _disableKeyboardWhileBusy:
1337 # Restore previous focus window for this toplevel window,
1338 # but only if is still set to the busy window (it may have
1339 # been changed).
1340 windowFocusNow = window.tk.call('focus', '-lastfor', window._w)
1341 if windowFocusNow == winInfo['busyWindow']:
1342 try:
1343 window.tk.call('focus', winInfo['windowFocus'])
1344 except Tkinter.TclError:
1345 # Previous focus widget has been deleted. Set focus
1346 # to toplevel window instead (can't leave focus on
1347 # busy window).
1348 window.focus_set()
1349
1350 if _disableKeyboardWhileBusy:
1351 # Restore the focus, depending on whether the focus had changed
1352 # between the calls to showbusycursor and hidebusycursor.
1353 if forceFocusRestore or busyInfo['busyFocus'] == currentFocus:
1354 # The focus had not changed, so restore it to as it was before
1355 # the call to showbusycursor,
1356 previousFocus = busyInfo['previousFocus']
1357 if previousFocus is not None:
1358 try:
1359 root.tk.call('focus', previousFocus)
1360 except Tkinter.TclError:
1361 # Previous focus widget has been deleted; forget it.
1362 pass
1363 else:
1364 # The focus had changed, so restore it to what it had been
1365 # changed to before the call to hidebusycursor.
1366 root.tk.call('focus', currentFocus)
1367
1368 def clearbusycursor():
1369 while len(_busyStack) > 0:
1370 hidebusycursor()
1371
1372 def setbusycursorattributes(window, **kw):
1373 _addRootToToplevelBusyInfo()
1374 for name, value in kw.items():
1375 if name == 'exclude':
1376 _toplevelBusyInfo[window]['excludeFromBusy'] = value
1377 elif name == 'cursorName':
1378 _toplevelBusyInfo[window]['busyCursorName'] = value
1379 else:
1380 raise KeyError('Unknown busycursor attribute "' + name + '"')
1381
1382 def _addRootToToplevelBusyInfo():
1383 # Include the Tk root window in the list of toplevels. This must
1384 # not be called before Tkinter has had a chance to be initialised by
1385 # the application.
1386
1387 root = Tkinter._default_root
1388 if root == None:
1389 root = Tkinter.Tk()
1390 if root not in _toplevelBusyInfo:
1391 _addToplevelBusyInfo(root)
1392
1393 def busycallback(command, updateFunction = None):
1394 if not hasattr(command, '__call__'):
1395 raise ValueError('cannot register non-command busy callback %s %s' % \
1396 (repr(command), type(command)))
1397 wrapper = _BusyWrapper(command, updateFunction)
1398 return wrapper.callback
1399
1400 _errorReportFile = None
1401 _errorWindow = None
1402
1403 def reporterrorstofile(file = None):
1404 global _errorReportFile
1405 _errorReportFile = file
1406
1407 def displayerror(text):
1408 global _errorWindow
1409
1410 if _errorReportFile is not None:
1411 _errorReportFile.write(text + '\n')
1412 else:
1413 # Print error on standard error as well as to error window.
1414 # Useful if error window fails to be displayed, for example
1415 # when exception is triggered in a <Destroy> binding for root
1416 # window.
1417 sys.stderr.write(text + '\n')
1418
1419 if _errorWindow is None:
1420 # The error window has not yet been created.
1421 _errorWindow = _ErrorWindow()
1422
1423 _errorWindow.showerror(text)
1424
1425 _root = None
1426 _disableKeyboardWhileBusy = 1
1427
1428 def initialise(
1429 root = None,
1430 size = None,
1431 fontScheme = None,
1432 useTkOptionDb = 0,
1433 noBltBusy = 0,
1434 disableKeyboardWhileBusy = None,
1435 ):
1436 # Remember if show/hidebusycursor should ignore keyboard events.
1437 global _disableKeyboardWhileBusy
1438 if disableKeyboardWhileBusy is not None:
1439 _disableKeyboardWhileBusy = disableKeyboardWhileBusy
1440
1441 # Do not use blt busy command if noBltBusy is set. Otherwise,
1442 # use blt busy if it is available.
1443 global _haveBltBusy
1444 if noBltBusy:
1445 _haveBltBusy = 0
1446
1447 # Save flag specifying whether the Tk option database should be
1448 # queried when setting megawidget option default values.
1449 global _useTkOptionDb
1450 _useTkOptionDb = useTkOptionDb
1451
1452 # If we haven't been given a root window, use the default or
1453 # create one.
1454 if root is None:
1455 if Tkinter._default_root is None:
1456 root = Tkinter.Tk()
1457 else:
1458 root = Tkinter._default_root
1459
1460 # If this call is initialising a different Tk interpreter than the
1461 # last call, then re-initialise all global variables. Assume the
1462 # last interpreter has been destroyed - ie: Pmw does not (yet)
1463 # support multiple simultaneous interpreters.
1464 global _root
1465 if _root is not None and _root != root:
1466 global _busyStack
1467 global _errorWindow
1468 global _grabStack
1469 global _hullToMegaWidget
1470 global _toplevelBusyInfo
1471 _busyStack = []
1472 _errorWindow = None
1473 _grabStack = []
1474 _hullToMegaWidget = {}
1475 _toplevelBusyInfo = {}
1476 _root = root
1477
1478 # Trap Tkinter Toplevel constructors so that a list of Toplevels
1479 # can be maintained.
1480 Tkinter.Toplevel.title = __TkinterToplevelTitle
1481
1482 # Trap Tkinter widget destruction so that megawidgets can be
1483 # destroyed when their hull widget is destoyed and the list of
1484 # Toplevels can be pruned.
1485 Tkinter.Toplevel.destroy = __TkinterToplevelDestroy
1486 Tkinter.Widget.destroy = __TkinterWidgetDestroy
1487
1488 # Modify Tkinter's CallWrapper class to improve the display of
1489 # errors which occur in callbacks.
1490 Tkinter.CallWrapper = __TkinterCallWrapper
1491
1492 # Make sure we get to know when the window manager deletes the
1493 # root window. Only do this if the protocol has not yet been set.
1494 # This is required if there is a modal dialog displayed and the
1495 # window manager deletes the root window. Otherwise the
1496 # application will not exit, even though there are no windows.
1497 if root.protocol('WM_DELETE_WINDOW') == '':
1498 root.protocol('WM_DELETE_WINDOW', root.destroy)
1499
1500 # Set the base font size for the application and set the
1501 # Tk option database font resources.
1502
1503 _font_initialise(root, size, fontScheme)
1504
1505 return root
1506
1507 def alignlabels(widgets, sticky = None):
1508 if len(widgets) == 0:
1509 return
1510
1511 widgets[0].update_idletasks()
1512
1513 # Determine the size of the maximum length label string.
1514 maxLabelWidth = 0
1515 for iwid in widgets:
1516 labelWidth = iwid.grid_bbox(0, 1)[2]
1517 if labelWidth > maxLabelWidth:
1518 maxLabelWidth = labelWidth
1519
1520 # Adjust the margins for the labels such that the child sites and
1521 # labels line up.
1522 for iwid in widgets:
1523 if sticky is not None:
1524 iwid.component('label').grid(sticky=sticky)
1525 iwid.grid_columnconfigure(0, minsize = maxLabelWidth)
1526 #=============================================================================
1527
1528 # Private routines
1529 #-----------------
1530 _callToTkReturned = 1
1531 _recursionCounter = 1
1532
1533 class _TraceTk:
1534 def __init__(self, tclInterp):
1535 self.tclInterp = tclInterp
1536
1537 def getTclInterp(self):
1538 return self.tclInterp
1539
1540 # Calling from python into Tk.
1541 def call(self, *args, **kw):
1542 global _callToTkReturned
1543 global _recursionCounter
1544
1545 _callToTkReturned = 0
1546 if len(args) == 1 and isinstance(args[0], tuple):
1547 argStr = str(args[0])
1548 else:
1549 argStr = str(args)
1550 _traceTkFile.write('CALL TK> %d:%s%s' %
1551 (_recursionCounter, ' ' * _recursionCounter, argStr))
1552 _recursionCounter = _recursionCounter + 1
1553 try:
1554 result = self.tclInterp.call(*args, **kw)
1555 except Tkinter.TclError:
1556 errorString = sys.exc_info()[1]
1557 _callToTkReturned = 1
1558 _recursionCounter = _recursionCounter - 1
1559 _traceTkFile.write('\nTK ERROR> %d:%s-> %s\n' %
1560 (_recursionCounter, ' ' * _recursionCounter,
1561 repr(errorString)))
1562 if _withStackTrace:
1563 _traceTkFile.write('CALL TK> stack:\n')
1564 traceback.print_stack()
1565 raise Tkinter.TclError(errorString)
1566
1567 _recursionCounter = _recursionCounter - 1
1568 if _callToTkReturned:
1569 _traceTkFile.write('CALL RTN> %d:%s-> %s' %
1570 (_recursionCounter, ' ' * _recursionCounter, repr(result)))
1571 else:
1572 _callToTkReturned = 1
1573 if result:
1574 _traceTkFile.write(' -> %s' % repr(result))
1575 _traceTkFile.write('\n')
1576 if _withStackTrace:
1577 _traceTkFile.write('CALL TK> stack:\n')
1578 traceback.print_stack()
1579
1580 _traceTkFile.flush()
1581 return result
1582
1583 def __getattr__(self, key):
1584 return getattr(self.tclInterp, key)
1585
1586 def _setTkInterps(window, tk):
1587 window.tk = tk
1588 for child in window.children.values():
1589 _setTkInterps(child, tk)
1590
1591 #=============================================================================
1592
1593 # Functions to display a busy cursor. Keep a list of all toplevels
1594 # and display the busy cursor over them. The list will contain the Tk
1595 # root toplevel window as well as all other toplevel windows.
1596 # Also keep a list of the widget which last had focus for each
1597 # toplevel.
1598
1599 # Map from toplevel windows to
1600 # {'isBusy', 'windowFocus', 'busyWindow',
1601 # 'excludeFromBusy', 'busyCursorName'}
1602 _toplevelBusyInfo = {}
1603
1604 # Pmw needs to know all toplevel windows, so that it can call blt busy
1605 # on them. This is a hack so we get notified when a Tk topevel is
1606 # created. Ideally, the __init__ 'method' should be overridden, but
1607 # it is a 'read-only special attribute'. Luckily, title() is always
1608 # called from the Tkinter Toplevel constructor.
1609
1610 def _addToplevelBusyInfo(window):
1611 if window._w == '.':
1612 busyWindow = '._Busy'
1613 else:
1614 busyWindow = window._w + '._Busy'
1615
1616 _toplevelBusyInfo[window] = {
1617 'isBusy' : 0,
1618 'windowFocus' : None,
1619 'busyWindow' : busyWindow,
1620 'excludeFromBusy' : 0,
1621 'busyCursorName' : None,
1622 }
1623
1624 def __TkinterToplevelTitle(self, *args):
1625 # If this is being called from the constructor, include this
1626 # Toplevel in the list of toplevels and set the initial
1627 # WM_DELETE_WINDOW protocol to destroy() so that we get to know
1628 # about it.
1629 if self not in _toplevelBusyInfo:
1630 _addToplevelBusyInfo(self)
1631 self._Pmw_WM_DELETE_name = self.register(self.destroy, None, 0)
1632 self.protocol('WM_DELETE_WINDOW', self._Pmw_WM_DELETE_name)
1633
1634 return Tkinter.Wm.title(*(self,) + args)
1635
1636 _haveBltBusy = None
1637 def _havebltbusy(window):
1638 global _busy_hold, _busy_release, _haveBltBusy
1639 if _haveBltBusy is None:
1640 import PmwBlt
1641 _haveBltBusy = PmwBlt.havebltbusy(window)
1642 _busy_hold = PmwBlt.busy_hold
1643 if os.name == 'nt':
1644 # There is a bug in Blt 2.4i on NT where the busy window
1645 # does not follow changes in the children of a window.
1646 # Using forget works around the problem.
1647 _busy_release = PmwBlt.busy_forget
1648 else:
1649 _busy_release = PmwBlt.busy_release
1650 return _haveBltBusy
1651
1652 class _BusyWrapper:
1653 def __init__(self, command, updateFunction):
1654 self._command = command
1655 self._updateFunction = updateFunction
1656
1657 def callback(self, *args):
1658 showbusycursor()
1659 rtn = self._command(*args)
1660
1661 # Call update before hiding the busy windows to clear any
1662 # events that may have occurred over the busy windows.
1663 if hasattr(self._updateFunction, '__call__'):
1664 self._updateFunction()
1665
1666 hidebusycursor()
1667 return rtn
1668
1669 #=============================================================================
1670
1671 def drawarrow(canvas, color, direction, tag, baseOffset = 0.25, edgeOffset = 0.15):
1672 canvas.delete(tag)
1673
1674 bw = (int(canvas['borderwidth']) +
1675 int(canvas['highlightthickness']))
1676 width = int(canvas['width'])
1677 height = int(canvas['height'])
1678
1679 if direction in ('up', 'down'):
1680 majorDimension = height
1681 minorDimension = width
1682 else:
1683 majorDimension = width
1684 minorDimension = height
1685
1686 offset = round(baseOffset * majorDimension)
1687 if direction in ('down', 'right'):
1688 base = bw + offset
1689 apex = bw + majorDimension - offset
1690 else:
1691 base = bw + majorDimension - offset
1692 apex = bw + offset
1693
1694 if minorDimension > 3 and minorDimension % 2 == 0:
1695 minorDimension = minorDimension - 1
1696 half = int(minorDimension * (1 - 2 * edgeOffset)) / 2
1697 low = round(bw + edgeOffset * minorDimension)
1698 middle = low + half
1699 high = low + 2 * half
1700
1701 if direction in ('up', 'down'):
1702 coords = (low, base, high, base, middle, apex)
1703 else:
1704 coords = (base, low, base, high, apex, middle)
1705 kw = {'fill' : color, 'outline' : color, 'tag' : tag}
1706 canvas.create_polygon(*coords, **kw)
1707
1708 #=============================================================================
1709
1710 # Modify the Tkinter destroy methods so that it notifies us when a Tk
1711 # toplevel or frame is destroyed.
1712
1713 # A map from the 'hull' component of a megawidget to the megawidget.
1714 # This is used to clean up a megawidget when its hull is destroyed.
1715 _hullToMegaWidget = {}
1716
1717 def __TkinterToplevelDestroy(tkWidget):
1718 if tkWidget in _hullToMegaWidget:
1719 mega = _hullToMegaWidget[tkWidget]
1720 try:
1721 mega.destroy()
1722 except:
1723 _reporterror(mega.destroy, ())
1724 else:
1725 # Delete the busy info structure for this toplevel (if the
1726 # window was created before initialise() was called, it
1727 # will not have any.
1728 if tkWidget in _toplevelBusyInfo:
1729 del _toplevelBusyInfo[tkWidget]
1730 if hasattr(tkWidget, '_Pmw_WM_DELETE_name'):
1731 tkWidget.tk.deletecommand(tkWidget._Pmw_WM_DELETE_name)
1732 del tkWidget._Pmw_WM_DELETE_name
1733 Tkinter.BaseWidget.destroy(tkWidget)
1734
1735 def __TkinterWidgetDestroy(tkWidget):
1736 if tkWidget in _hullToMegaWidget:
1737 mega = _hullToMegaWidget[tkWidget]
1738 try:
1739 mega.destroy()
1740 except:
1741 _reporterror(mega.destroy, ())
1742 else:
1743 Tkinter.BaseWidget.destroy(tkWidget)
1744
1745 #=============================================================================
1746
1747 # Add code to Tkinter to improve the display of errors which occur in
1748 # callbacks.
1749
1750 class __TkinterCallWrapper:
1751 def __init__(self, func, subst, widget):
1752 self.func = func
1753 self.subst = subst
1754 self.widget = widget
1755
1756 # Calling back from Tk into python.
1757 def __call__(self, *args):
1758 try:
1759 if self.subst:
1760 args = self.subst(*args)
1761 if _traceTk:
1762 if not _callToTkReturned:
1763 _traceTkFile.write('\n')
1764 if hasattr(self.func, 'im_class'):
1765 name = self.func.im_class.__name__ + '.' + \
1766 self.func.__name__
1767 else:
1768 name = self.func.__name__
1769 if len(args) == 1 and hasattr(args[0], 'type'):
1770 # The argument to the callback is an event.
1771 eventName = _eventTypeToName[int(args[0].type)]
1772 if eventName in ('KeyPress', 'KeyRelease',):
1773 argStr = '(%s %s Event: %s)' % \
1774 (eventName, args[0].keysym, args[0].widget)
1775 else:
1776 argStr = '(%s Event, %s)' % (eventName, args[0].widget)
1777 else:
1778 argStr = str(args)
1779 _traceTkFile.write('CALLBACK> %d:%s%s%s\n' %
1780 (_recursionCounter, ' ' * _recursionCounter, name, argStr))
1781 _traceTkFile.flush()
1782 return self.func(*args)
1783 except SystemExit:
1784 msg = sys.exc_info()[1]
1785 raise SystemExit(msg)
1786 except:
1787 _reporterror(self.func, args)
1788
1789 _eventTypeToName = {
1790 2 : 'KeyPress', 15 : 'VisibilityNotify', 28 : 'PropertyNotify',
1791 3 : 'KeyRelease', 16 : 'CreateNotify', 29 : 'SelectionClear',
1792 4 : 'ButtonPress', 17 : 'DestroyNotify', 30 : 'SelectionRequest',
1793 5 : 'ButtonRelease', 18 : 'UnmapNotify', 31 : 'SelectionNotify',
1794 6 : 'MotionNotify', 19 : 'MapNotify', 32 : 'ColormapNotify',
1795 7 : 'EnterNotify', 20 : 'MapRequest', 33 : 'ClientMessage',
1796 8 : 'LeaveNotify', 21 : 'ReparentNotify', 34 : 'MappingNotify',
1797 9 : 'FocusIn', 22 : 'ConfigureNotify', 35 : 'VirtualEvents',
1798 10 : 'FocusOut', 23 : 'ConfigureRequest', 36 : 'ActivateNotify',
1799 11 : 'KeymapNotify', 24 : 'GravityNotify', 37 : 'DeactivateNotify',
1800 12 : 'Expose', 25 : 'ResizeRequest', 38 : 'MouseWheelEvent',
1801 13 : 'GraphicsExpose', 26 : 'CirculateNotify',
1802 14 : 'NoExpose', 27 : 'CirculateRequest',
1803 }
1804
1805 def _reporterror(func, args):
1806 # Fetch current exception values.
1807 exc_type, exc_value, exc_traceback = sys.exc_info()
1808
1809 # Give basic information about the callback exception.
1810 class _C:
1811 def _m(self): pass
1812 if isinstance(exc_type, type(_C)):
1813 # Handle python 1.5 class exceptions.
1814 exc_type = exc_type.__name__
1815 msg = str(exc_type) + ' Exception in Tk callback\n'
1816 msg = msg + ' Function: %s (type: %s)\n' % (repr(func), type(func))
1817 msg = msg + ' Args: %s\n' % str(args)
1818
1819 if isinstance(args, tuple) and len(args) > 0 and \
1820 hasattr(args[0], 'type'):
1821 eventArg = 1
1822 else:
1823 eventArg = 0
1824
1825 # If the argument to the callback is an event, add the event type.
1826 if eventArg:
1827 eventNum = int(args[0].type)
1828 if eventNum in _eventTypeToName:
1829 msg = msg + ' Event type: %s (type num: %d)\n' % \
1830 (_eventTypeToName[eventNum], eventNum)
1831 else:
1832 msg = msg + ' Unknown event type (type num: %d)\n' % eventNum
1833
1834 # Add the traceback.
1835 msg = msg + 'Traceback (innermost last):\n'
1836 for tr in traceback.extract_tb(exc_traceback):
1837 msg = msg + ' File "%s", line %s, in %s\n' % (tr[0], tr[1], tr[2])
1838 msg = msg + ' %s\n' % tr[3]
1839 msg = msg + '%s: %s\n' % (exc_type, exc_value)
1840
1841 # If the argument to the callback is an event, add the event contents.
1842 if eventArg:
1843 msg = msg + '\n================================================\n'
1844 msg = msg + ' Event contents:\n'
1845 keys = list(args[0].__dict__)
1846 keys.sort()
1847 for key in keys:
1848 msg = msg + ' %s: %s\n' % (key, args[0].__dict__[key])
1849
1850 clearbusycursor()
1851 try:
1852 displayerror(msg)
1853 except:
1854 pass
1855
1856 class _ErrorWindow:
1857 def __init__(self):
1858
1859 self._errorQueue = []
1860 self._errorCount = 0
1861 self._open = 0
1862 self._firstShowing = 1
1863
1864 # Create the toplevel window
1865 self._top = Tkinter.Toplevel()
1866 self._top.protocol('WM_DELETE_WINDOW', self._hide)
1867 self._top.title('Error in background function')
1868 self._top.iconname('Background error')
1869
1870 # Create the text widget and scrollbar in a frame
1871 upperframe = Tkinter.Frame(self._top)
1872
1873 scrollbar = Tkinter.Scrollbar(upperframe, orient='vertical')
1874 scrollbar.pack(side = 'right', fill = 'y')
1875
1876 self._text = Tkinter.Text(upperframe, yscrollcommand=scrollbar.set)
1877 self._text.pack(fill = 'both', expand = 1)
1878 scrollbar.configure(command=self._text.yview)
1879
1880 # Create the buttons and label in a frame
1881 lowerframe = Tkinter.Frame(self._top)
1882
1883 ignore = Tkinter.Button(lowerframe,
1884 text = 'Ignore remaining errors', command = self._hide)
1885 ignore.pack(side='left')
1886
1887 self._nextError = Tkinter.Button(lowerframe,
1888 text = 'Show next error', command = self._next)
1889 self._nextError.pack(side='left')
1890
1891 self._label = Tkinter.Label(lowerframe, relief='ridge')
1892 self._label.pack(side='left', fill='x', expand=1)
1893
1894 # Pack the lower frame first so that it does not disappear
1895 # when the window is resized.
1896 lowerframe.pack(side = 'bottom', fill = 'x')
1897 upperframe.pack(side = 'bottom', fill = 'both', expand = 1)
1898
1899 def showerror(self, text):
1900 if self._open:
1901 self._errorQueue.append(text)
1902 else:
1903 self._display(text)
1904 self._open = 1
1905
1906 # Display the error window in the same place it was before.
1907 if self._top.state() == 'normal':
1908 # If update_idletasks is not called here, the window may
1909 # be placed partially off the screen. Also, if it is not
1910 # called and many errors are generated quickly in
1911 # succession, the error window may not display errors
1912 # until the last one is generated and the interpreter
1913 # becomes idle.
1914 # XXX: remove this, since it causes omppython to go into an
1915 # infinite loop if an error occurs in an omp callback.
1916 # self._top.update_idletasks()
1917
1918 pass
1919 else:
1920 if self._firstShowing:
1921 geom = None
1922 else:
1923 geometry = self._top.geometry()
1924 index = geometry.find('+')
1925 if index >= 0:
1926 geom = geometry[index:]
1927 else:
1928 geom = None
1929 setgeometryanddeiconify(self._top, geom)
1930
1931 if self._firstShowing:
1932 self._firstShowing = 0
1933 else:
1934 self._top.tkraise()
1935
1936 self._top.focus()
1937
1938 self._updateButtons()
1939
1940 # Release any grab, so that buttons in the error window work.
1941 releasegrabs()
1942
1943 def _hide(self):
1944 self._errorCount = self._errorCount + len(self._errorQueue)
1945 self._errorQueue = []
1946 self._top.withdraw()
1947 self._open = 0
1948
1949 def _next(self):
1950 # Display the next error in the queue.
1951
1952 text = self._errorQueue[0]
1953 del self._errorQueue[0]
1954
1955 self._display(text)
1956 self._updateButtons()
1957
1958 def _display(self, text):
1959 self._errorCount = self._errorCount + 1
1960 text = 'Error: %d\n%s' % (self._errorCount, text)
1961 self._text.delete('1.0', 'end')
1962 self._text.insert('end', text)
1963
1964 def _updateButtons(self):
1965 numQueued = len(self._errorQueue)
1966 if numQueued > 0:
1967 self._label.configure(text='%d more errors' % numQueued)
1968 self._nextError.configure(state='normal')
1969 else:
1970 self._label.configure(text='No more errors')
1971 self._nextError.configure(state='disabled')
1972
1973 ######################################################################
1974 ### File: PmwDialog.py
1975 # Based on iwidgets2.2.0/dialog.itk and iwidgets2.2.0/dialogshell.itk code.
1976
1977 # Convention:
1978 # Each dialog window should have one of these as the rightmost button:
1979 # Close Close a window which only displays information.
1980 # Cancel Close a window which may be used to change the state of
1981 # the application.
1982
1983 import sys
1984
1985
1986 # A Toplevel with a ButtonBox and child site.
1987
1988 class Dialog(MegaToplevel):
1989 def __init__(self, parent = None, **kw):
1990
1991 # Define the megawidget options.
1992
1993 optiondefs = (
1994 ('buttonbox_hull_borderwidth', 1, None),
1995 ('buttonbox_hull_relief', 'raised', None),
1996 ('buttonboxpos', 's', INITOPT),
1997 ('buttons', ('OK',), self._buttons),
1998 ('command', None, None),
1999 ('dialogchildsite_borderwidth', 1, None),
2000 ('dialogchildsite_relief', 'raised', None),
2001 ('defaultbutton', None, self._defaultButton),
2002 ('master', 'parent', None),
2003 ('separatorwidth', 0, INITOPT),
2004 )
2005 self.defineoptions(kw, optiondefs)
2006
2007 # Initialise the base class (after defining the options).
2008 MegaToplevel.__init__(self, parent)
2009
2010 # Create the components.
2011
2012 oldInterior = MegaToplevel.interior(self)
2013
2014 # Set up pack options according to the position of the button box.
2015 pos = self['buttonboxpos']
2016 if pos not in 'nsew':
2017 raise ValueError('bad buttonboxpos option "%s": should be n, s, e, or w' \
2018 % pos)
2019
2020 if pos in 'ns':
2021 orient = 'horizontal'
2022 fill = 'x'
2023 if pos == 'n':
2024 side = 'top'
2025 else:
2026 side = 'bottom'
2027 else:
2028 orient = 'vertical'
2029 fill = 'y'
2030 if pos == 'w':
2031 side = 'left'
2032 else:
2033 side = 'right'
2034
2035 # Create the button box.
2036 self._buttonBox = self.createcomponent('buttonbox',
2037 (), None,
2038 ButtonBox, (oldInterior,), orient = orient)
2039 self._buttonBox.pack(side = side, fill = fill)
2040
2041 # Create the separating line.
2042 width = self['separatorwidth']
2043 if width > 0:
2044 self._separator = self.createcomponent('separator',
2045 (), None,
2046 Tkinter.Frame, (oldInterior,), relief = 'sunken',
2047 height = width, width = width, borderwidth = width / 2)
2048 self._separator.pack(side = side, fill = fill)
2049
2050 # Create the child site.
2051 self.__dialogChildSite = self.createcomponent('dialogchildsite',
2052 (), None,
2053 Tkinter.Frame, (oldInterior,))
2054 self.__dialogChildSite.pack(side=side, fill='both', expand=1)
2055
2056 self.oldButtons = ()
2057 self.oldDefault = None
2058
2059 self.bind('<Return>', self._invokeDefault)
2060 self.userdeletefunc(self._doCommand)
2061 self.usermodaldeletefunc(self._doCommand)
2062
2063 # Check keywords and initialise options.
2064 self.initialiseoptions()
2065
2066 def interior(self):
2067 return self.__dialogChildSite
2068
2069 def invoke(self, index = DEFAULT):
2070 return self._buttonBox.invoke(index)
2071
2072 def _invokeDefault(self, event):
2073 try:
2074 self._buttonBox.index(DEFAULT)
2075 except ValueError:
2076 return
2077 self._buttonBox.invoke()
2078
2079 def _doCommand(self, name = None):
2080 if name is not None and self.active() and \
2081 grabstacktopwindow() != self.component('hull'):
2082 # This is a modal dialog but is not on the top of the grab
2083 # stack (ie: should not have the grab), so ignore this
2084 # event. This seems to be a bug in Tk and may occur in
2085 # nested modal dialogs.
2086 #
2087 # An example is the PromptDialog demonstration. To
2088 # trigger the problem, start the demo, then move the mouse
2089 # to the main window, hit <TAB> and then <TAB> again. The
2090 # highlight border of the "Show prompt dialog" button
2091 # should now be displayed. Now hit <SPACE>, <RETURN>,
2092 # <RETURN> rapidly several times. Eventually, hitting the
2093 # return key invokes the password dialog "OK" button even
2094 # though the confirm dialog is active (and therefore
2095 # should have the keyboard focus). Observed under Solaris
2096 # 2.5.1, python 1.5.2 and Tk8.0.
2097
2098 # TODO: Give focus to the window on top of the grabstack.
2099 return
2100
2101 command = self['command']
2102 if hasattr(command, '__call__'):
2103 return command(name)
2104 else:
2105 if self.active():
2106 self.deactivate(name)
2107 else:
2108 self.withdraw()
2109
2110 def _buttons(self):
2111 buttons = self['buttons']
2112 if not isinstance(buttons, (tuple, list)):
2113 raise ValueError('bad buttons option "%s": should be a tuple' % str(buttons))
2114 if self.oldButtons == buttons:
2115 return
2116
2117 self.oldButtons = buttons
2118
2119 for index in range(self._buttonBox.numbuttons()):
2120 self._buttonBox.delete(0)
2121 for name in buttons:
2122 self._buttonBox.add(name,
2123 command=lambda self=self, name=name: self._doCommand(name))
2124
2125 if len(buttons) > 0:
2126 defaultbutton = self['defaultbutton']
2127 if defaultbutton is None:
2128 self._buttonBox.setdefault(None)
2129 else:
2130 try:
2131 self._buttonBox.index(defaultbutton)
2132 except ValueError:
2133 pass
2134 else:
2135 self._buttonBox.setdefault(defaultbutton)
2136 self._buttonBox.alignbuttons()
2137
2138 def _defaultButton(self):
2139 defaultbutton = self['defaultbutton']
2140 if self.oldDefault == defaultbutton:
2141 return
2142
2143 self.oldDefault = defaultbutton
2144
2145 if len(self['buttons']) > 0:
2146 if defaultbutton is None:
2147 self._buttonBox.setdefault(None)
2148 else:
2149 try:
2150 self._buttonBox.index(defaultbutton)
2151 except ValueError:
2152 pass
2153 else:
2154 self._buttonBox.setdefault(defaultbutton)
2155
2156 ######################################################################
2157 ### File: PmwTimeFuncs.py
2158 # Functions for dealing with dates and times.
2159
2160 import re
2161
2162 def timestringtoseconds(text, separator = ':'):
2163 inputList = text.strip().split(separator)
2164 if len(inputList) != 3:
2165 raise ValueError('invalid value: ' + text)
2166
2167 sign = 1
2168 if len(inputList[0]) > 0 and inputList[0][0] in ('+', '-'):
2169 if inputList[0][0] == '-':
2170 sign = -1
2171 inputList[0] = inputList[0][1:]
2172
2173 if re.search('[^0-9]', ''.join(inputList)) is not None:
2174 raise ValueError('invalid value: ' + text)
2175
2176 hour = int(inputList[0])
2177 minute = int(inputList[1])
2178 second = int(inputList[2])
2179
2180 if minute >= 60 or second >= 60:
2181 raise ValueError('invalid value: ' + text)
2182 return sign * (hour * 60 * 60 + minute * 60 + second)
2183
2184 _year_pivot = 50
2185 _century = 2000
2186
2187 def setyearpivot(pivot, century = None):
2188 global _year_pivot
2189 global _century
2190 oldvalues = (_year_pivot, _century)
2191 _year_pivot = pivot
2192 if century is not None:
2193 _century = century
2194 return oldvalues
2195
2196 def datestringtojdn(text, format = 'ymd', separator = '/'):
2197 inputList = text.strip().split(separator)
2198 if len(inputList) != 3:
2199 raise ValueError('invalid value: ' + text)
2200
2201 if re.search('[^0-9]', ''.join(inputList)) is not None:
2202 raise ValueError('invalid value: ' + text)
2203 formatList = list(format)
2204 day = int(inputList[formatList.index('d')])
2205 month = int(inputList[formatList.index('m')])
2206 year = int(inputList[formatList.index('y')])
2207
2208 if _year_pivot is not None:
2209 if year >= 0 and year < 100:
2210 if year <= _year_pivot:
2211 year = year + _century
2212 else:
2213 year = year + _century - 100
2214
2215 jdn = ymdtojdn(year, month, day)
2216 if jdntoymd(jdn) != (year, month, day):
2217 raise ValueError('invalid value: ' + text)
2218 return jdn
2219
2220 def _cdiv(a, b):
2221 # Return a / b as calculated by most C language implementations,
2222 # assuming both a and b are integers.
2223
2224 if a * b > 0:
2225 return a / b
2226 else:
2227 return -(abs(a) / abs(b))
2228
2229 def ymdtojdn(year, month, day, julian = -1, papal = 1):
2230
2231 # set Julian flag if auto set
2232 if julian < 0:
2233 if papal: # Pope Gregory XIII's decree
2234 lastJulianDate = 15821004 # last day to use Julian calendar
2235 else: # British-American usage
2236 lastJulianDate = 17520902 # last day to use Julian calendar
2237
2238 julian = ((year * 100) + month) * 100 + day <= lastJulianDate
2239
2240 if year < 0:
2241 # Adjust BC year
2242 year = year + 1
2243
2244 if julian:
2245 return 367 * year - _cdiv(7 * (year + 5001 + _cdiv((month - 9), 7)), 4) + \
2246 _cdiv(275 * month, 9) + day + 1729777
2247 else:
2248 return (day - 32076) + \
2249 _cdiv(1461 * (year + 4800 + _cdiv((month - 14), 12)), 4) + \
2250 _cdiv(367 * (month - 2 - _cdiv((month - 14), 12) * 12), 12) - \
2251 _cdiv((3 * _cdiv((year + 4900 + _cdiv((month - 14), 12)), 100)), 4) + \
2252 1 # correction by rdg
2253
2254 def jdntoymd(jdn, julian = -1, papal = 1):
2255
2256 # set Julian flag if auto set
2257 if julian < 0:
2258 if papal: # Pope Gregory XIII's decree
2259 lastJulianJdn = 2299160 # last jdn to use Julian calendar
2260 else: # British-American usage
2261 lastJulianJdn = 2361221 # last jdn to use Julian calendar
2262
2263 julian = (jdn <= lastJulianJdn);
2264
2265 x = jdn + 68569
2266 if julian:
2267 x = x + 38
2268 daysPer400Years = 146100
2269 fudgedDaysPer4000Years = 1461000 + 1
2270 else:
2271 daysPer400Years = 146097
2272 fudgedDaysPer4000Years = 1460970 + 31
2273
2274 z = _cdiv(4 * x, daysPer400Years)
2275 x = x - _cdiv((daysPer400Years * z + 3), 4)
2276 y = _cdiv(4000 * (x + 1), fudgedDaysPer4000Years)
2277 x = x - _cdiv(1461 * y, 4) + 31
2278 m = _cdiv(80 * x, 2447)
2279 d = x - _cdiv(2447 * m, 80)
2280 x = _cdiv(m, 11)
2281 m = m + 2 - 12 * x
2282 y = 100 * (z - 49) + y + x
2283
2284 # Convert from longs to integers.
2285 yy = int(y)
2286 mm = int(m)
2287 dd = int(d)
2288
2289 if yy <= 0:
2290 # Adjust BC years.
2291 yy = yy - 1
2292
2293 return (yy, mm, dd)
2294
2295 def stringtoreal(text, separator = '.'):
2296 if separator != '.':
2297 if text.find('.') >= 0:
2298 raise ValueError('invalid value: ' + text)
2299 index = text.find(separator)
2300 if index >= 0:
2301 text = text[:index] + '.' + text[index + 1:]
2302 return float(text)
2303
2304 ######################################################################
2305 ### File: PmwBalloon.py
2306 import os
2307
2308
2309 class Balloon(MegaToplevel):
2310 def __init__(self, parent = None, **kw):
2311
2312 # Define the megawidget options.
2313 optiondefs = (
2314 ('initwait', 500, None), # milliseconds
2315 ('label_background', 'lightyellow', None),
2316 ('label_foreground', 'black', None),
2317 ('label_justify', 'left', None),
2318 ('master', 'parent', None),
2319 ('relmouse', 'none', self._relmouse),
2320 ('state', 'both', self._state),
2321 ('statuscommand', None, None),
2322 ('xoffset', 20, None), # pixels
2323 ('yoffset', 1, None), # pixels
2324 ('hull_highlightthickness', 1, None),
2325 ('hull_highlightbackground', 'black', None),
2326 )
2327 self.defineoptions(kw, optiondefs)
2328
2329 # Initialise the base class (after defining the options).
2330 MegaToplevel.__init__(self, parent)
2331
2332 self.withdraw()
2333 self.overrideredirect(1)
2334
2335 # Create the components.
2336 interior = self.interior()
2337 self._label = self.createcomponent('label',
2338 (), None,
2339 Tkinter.Label, (interior,))
2340 self._label.pack()
2341
2342 # The default hull configuration options give a black border
2343 # around the balloon, but avoids a black 'flash' when the
2344 # balloon is deiconified, before the text appears.
2345 if 'hull_background' not in kw:
2346 self.configure(hull_background = \
2347 str(self._label.cget('background')))
2348
2349 # Initialise instance variables.
2350 self._timer = None
2351
2352 # The widget or item that is currently triggering the balloon.
2353 # It is None if the balloon is not being displayed. It is a
2354 # one-tuple if the balloon is being displayed in response to a
2355 # widget binding (value is the widget). It is a two-tuple if
2356 # the balloon is being displayed in response to a canvas or
2357 # text item binding (value is the widget and the item).
2358 self._currentTrigger = None
2359
2360 # Check keywords and initialise options.
2361 self.initialiseoptions()
2362
2363 def destroy(self):
2364 if self._timer is not None:
2365 self.after_cancel(self._timer)
2366 self._timer = None
2367 MegaToplevel.destroy(self)
2368
2369 def bind(self, widget, balloonHelp, statusHelp = None):
2370
2371 # If a previous bind for this widget exists, remove it.
2372 self.unbind(widget)
2373
2374 if balloonHelp is None and statusHelp is None:
2375 return
2376
2377 if statusHelp is None:
2378 statusHelp = balloonHelp
2379 enterId = widget.bind('<Enter>',
2380 lambda event, self = self, w = widget,
2381 sHelp = statusHelp, bHelp = balloonHelp:
2382 self._enter(event, w, sHelp, bHelp, 0))
2383
2384 # Set Motion binding so that if the pointer remains at rest
2385 # within the widget until the status line removes the help and
2386 # then the pointer moves again, then redisplay the help in the
2387 # status line.
2388 # Note: The Motion binding only works for basic widgets, and
2389 # the hull of megawidgets but not for other megawidget components.
2390 motionId = widget.bind('<Motion>',
2391 lambda event = None, self = self, statusHelp = statusHelp:
2392 self.showstatus(statusHelp))
2393
2394 leaveId = widget.bind('<Leave>', self._leave)
2395 buttonId = widget.bind('<ButtonPress>', self._buttonpress)
2396
2397 # Set Destroy binding so that the balloon can be withdrawn and
2398 # the timer can be cancelled if the widget is destroyed.
2399 destroyId = widget.bind('<Destroy>', self._destroy)
2400
2401 # Use the None item in the widget's private Pmw dictionary to
2402 # store the widget's bind callbacks, for later clean up.
2403 if not hasattr(widget, '_Pmw_BalloonBindIds'):
2404 widget._Pmw_BalloonBindIds = {}
2405 widget._Pmw_BalloonBindIds[None] = \
2406 (enterId, motionId, leaveId, buttonId, destroyId)
2407
2408 def unbind(self, widget):
2409 if hasattr(widget, '_Pmw_BalloonBindIds'):
2410 if None in widget._Pmw_BalloonBindIds:
2411 (enterId, motionId, leaveId, buttonId, destroyId) = \
2412 widget._Pmw_BalloonBindIds[None]
2413 # Need to pass in old bindings, so that Tkinter can
2414 # delete the commands. Otherwise, memory is leaked.
2415 widget.unbind('<Enter>', enterId)
2416 widget.unbind('<Motion>', motionId)
2417 widget.unbind('<Leave>', leaveId)
2418 widget.unbind('<ButtonPress>', buttonId)
2419 widget.unbind('<Destroy>', destroyId)
2420 del widget._Pmw_BalloonBindIds[None]
2421
2422 if self._currentTrigger is not None and len(self._currentTrigger) == 1:
2423 # The balloon is currently being displayed and the current
2424 # trigger is a widget.
2425 triggerWidget = self._currentTrigger[0]
2426 if triggerWidget == widget:
2427 if self._timer is not None:
2428 self.after_cancel(self._timer)
2429 self._timer = None
2430 self.withdraw()
2431 self.clearstatus()
2432 self._currentTrigger = None
2433
2434 def tagbind(self, widget, tagOrItem, balloonHelp, statusHelp = None):
2435
2436 # If a previous bind for this widget's tagOrItem exists, remove it.
2437 self.tagunbind(widget, tagOrItem)
2438
2439 if balloonHelp is None and statusHelp is None:
2440 return
2441
2442 if statusHelp is None:
2443 statusHelp = balloonHelp
2444 enterId = widget.tag_bind(tagOrItem, '<Enter>',
2445 lambda event, self = self, w = widget,
2446 sHelp = statusHelp, bHelp = balloonHelp:
2447 self._enter(event, w, sHelp, bHelp, 1))
2448 motionId = widget.tag_bind(tagOrItem, '<Motion>',
2449 lambda event = None, self = self, statusHelp = statusHelp:
2450 self.showstatus(statusHelp))
2451 leaveId = widget.tag_bind(tagOrItem, '<Leave>', self._leave)
2452 buttonId = widget.tag_bind(tagOrItem, '<ButtonPress>', self._buttonpress)
2453
2454 # Use the tagOrItem item in the widget's private Pmw dictionary to
2455 # store the tagOrItem's bind callbacks, for later clean up.
2456 if not hasattr(widget, '_Pmw_BalloonBindIds'):
2457 widget._Pmw_BalloonBindIds = {}
2458 widget._Pmw_BalloonBindIds[tagOrItem] = \
2459 (enterId, motionId, leaveId, buttonId)
2460
2461 def tagunbind(self, widget, tagOrItem):
2462 if hasattr(widget, '_Pmw_BalloonBindIds'):
2463 if tagOrItem in widget._Pmw_BalloonBindIds:
2464 (enterId, motionId, leaveId, buttonId) = \
2465 widget._Pmw_BalloonBindIds[tagOrItem]
2466 widget.tag_unbind(tagOrItem, '<Enter>', enterId)
2467 widget.tag_unbind(tagOrItem, '<Motion>', motionId)
2468 widget.tag_unbind(tagOrItem, '<Leave>', leaveId)
2469 widget.tag_unbind(tagOrItem, '<ButtonPress>', buttonId)
2470 del widget._Pmw_BalloonBindIds[tagOrItem]
2471
2472 if self._currentTrigger is None:
2473 # The balloon is not currently being displayed.
2474 return
2475
2476 if len(self._currentTrigger) == 1:
2477 # The current trigger is a widget.
2478 return
2479
2480 if len(self._currentTrigger) == 2:
2481 # The current trigger is a canvas item.
2482 (triggerWidget, triggerItem) = self._currentTrigger
2483 if triggerWidget == widget and triggerItem == tagOrItem:
2484 if self._timer is not None:
2485 self.after_cancel(self._timer)
2486 self._timer = None
2487 self.withdraw()
2488 self.clearstatus()
2489 self._currentTrigger = None
2490 else: # The current trigger is a text item.
2491 (triggerWidget, x, y) = self._currentTrigger
2492 if triggerWidget == widget:
2493 currentPos = widget.index('@%d,%d' % (x, y))
2494 currentTags = widget.tag_names(currentPos)
2495 if tagOrItem in currentTags:
2496 if self._timer is not None:
2497 self.after_cancel(self._timer)
2498 self._timer = None
2499 self.withdraw()
2500 self.clearstatus()
2501 self._currentTrigger = None
2502
2503 def showstatus(self, statusHelp):
2504 if self['state'] in ('status', 'both'):
2505 cmd = self['statuscommand']
2506 if hasattr(cmd, '__call__'):
2507 cmd(statusHelp)
2508
2509 def clearstatus(self):
2510 self.showstatus(None)
2511
2512 def _state(self):
2513 if self['state'] not in ('both', 'balloon', 'status', 'none'):
2514 raise ValueError('bad state option ' + repr(self['state']) + \
2515 ': should be one of \'both\', \'balloon\', ' + \
2516 '\'status\' or \'none\'')
2517
2518 def _relmouse(self):
2519 if self['relmouse'] not in ('both', 'x', 'y', 'none'):
2520 raise ValueError('bad relmouse option ' + repr(self['relmouse'])+ \
2521 ': should be one of \'both\', \'x\', ' + '\'y\' or \'none\'')
2522
2523 def _enter(self, event, widget, statusHelp, balloonHelp, isItem):
2524
2525 # Do not display balloon if mouse button is pressed. This
2526 # will only occur if the button was pressed inside a widget,
2527 # then the mouse moved out of and then back into the widget,
2528 # with the button still held down. The number 0x1f00 is the
2529 # button mask for the 5 possible buttons in X.
2530 buttonPressed = (event.state & 0x1f00) != 0
2531
2532 if not buttonPressed and balloonHelp is not None and \
2533 self['state'] in ('balloon', 'both'):
2534 if self._timer is not None:
2535 self.after_cancel(self._timer)
2536 self._timer = None
2537
2538 self._timer = self.after(self['initwait'],
2539 lambda self = self, widget = widget, help = balloonHelp,
2540 isItem = isItem:
2541 self._showBalloon(widget, help, isItem))
2542
2543 if isItem:
2544 if hasattr(widget, 'canvasx'):
2545 # The widget is a canvas.
2546 item = widget.find_withtag('current')
2547 if len(item) > 0:
2548 item = item[0]
2549 else:
2550 item = None
2551 self._currentTrigger = (widget, item)
2552 else:
2553 # The widget is a text widget.
2554 self._currentTrigger = (widget, event.x, event.y)
2555 else:
2556 self._currentTrigger = (widget,)
2557
2558 self.showstatus(statusHelp)
2559
2560 def _leave(self, event):
2561 if self._timer is not None:
2562 self.after_cancel(self._timer)
2563 self._timer = None
2564 self.withdraw()
2565 self.clearstatus()
2566 self._currentTrigger = None
2567
2568 def _destroy(self, event):
2569
2570 # Only withdraw the balloon and cancel the timer if the widget
2571 # being destroyed is the widget that triggered the balloon.
2572 # Note that in a Tkinter Destroy event, the widget field is a
2573 # string and not a widget as usual.
2574
2575 if self._currentTrigger is None:
2576 # The balloon is not currently being displayed
2577 return
2578
2579 if len(self._currentTrigger) == 1:
2580 # The current trigger is a widget (not an item)
2581 triggerWidget = self._currentTrigger[0]
2582 if str(triggerWidget) == event.widget:
2583 if self._timer is not None:
2584 self.after_cancel(self._timer)
2585 self._timer = None
2586 self.withdraw()
2587 self.clearstatus()
2588 self._currentTrigger = None
2589
2590 def _buttonpress(self, event):
2591 if self._timer is not None:
2592 self.after_cancel(self._timer)
2593 self._timer = None
2594 self.withdraw()
2595 self._currentTrigger = None
2596
2597 def _showBalloon(self, widget, balloonHelp, isItem):
2598
2599 self._label.configure(text = balloonHelp)
2600
2601 # First, display the balloon offscreen to get dimensions.
2602 screenWidth = self.winfo_screenwidth()
2603 screenHeight = self.winfo_screenheight()
2604 self.geometry('+%d+0' % (screenWidth + 1))
2605 self.update_idletasks()
2606
2607 if isItem:
2608 # Get the bounding box of the current item.
2609 bbox = widget.bbox('current')
2610 if bbox is None:
2611 # The item that triggered the balloon has disappeared,
2612 # perhaps by a user's timer event that occured between
2613 # the <Enter> event and the 'initwait' timer calling
2614 # this method.
2615 return
2616
2617 # The widget is either a text or canvas. The meaning of
2618 # the values returned by the bbox method is different for
2619 # each, so use the existence of the 'canvasx' method to
2620 # distinguish between them.
2621 if hasattr(widget, 'canvasx'):
2622 # The widget is a canvas. Place balloon under canvas
2623 # item. The positions returned by bbox are relative
2624 # to the entire canvas, not just the visible part, so
2625 # need to convert to window coordinates.
2626 leftrel = bbox[0] - widget.canvasx(0)
2627 toprel = bbox[1] - widget.canvasy(0)
2628 bottomrel = bbox[3] - widget.canvasy(0)
2629 else:
2630 # The widget is a text widget. Place balloon under
2631 # the character closest to the mouse. The positions
2632 # returned by bbox are relative to the text widget
2633 # window (ie the visible part of the text only).
2634 leftrel = bbox[0]
2635 toprel = bbox[1]
2636 bottomrel = bbox[1] + bbox[3]
2637 else:
2638 leftrel = 0
2639 toprel = 0
2640 bottomrel = widget.winfo_height()
2641
2642 xpointer, ypointer = widget.winfo_pointerxy() # -1 if off screen
2643
2644 if xpointer >= 0 and self['relmouse'] in ('both', 'x'):
2645 x = xpointer
2646 else:
2647 x = leftrel + widget.winfo_rootx()
2648 x = x + self['xoffset']
2649
2650 if ypointer >= 0 and self['relmouse'] in ('both', 'y'):
2651 y = ypointer
2652 else:
2653 y = bottomrel + widget.winfo_rooty()
2654 y = y + self['yoffset']
2655
2656 edges = (int(str(self.cget('hull_highlightthickness'))) +
2657 int(str(self.cget('hull_borderwidth')))) * 2
2658 if x + self._label.winfo_reqwidth() + edges > screenWidth:
2659 x = screenWidth - self._label.winfo_reqwidth() - edges
2660
2661 if y + self._label.winfo_reqheight() + edges > screenHeight:
2662 if ypointer >= 0 and self['relmouse'] in ('both', 'y'):
2663 y = ypointer
2664 else:
2665 y = toprel + widget.winfo_rooty()
2666 y = y - self._label.winfo_reqheight() - self['yoffset'] - edges
2667
2668 setgeometryanddeiconify(self, '+%d+%d' % (x, y))
2669
2670 ######################################################################
2671 ### File: PmwButtonBox.py
2672 # Based on iwidgets2.2.0/buttonbox.itk code.
2673
2674
2675
2676 class ButtonBox(MegaWidget):
2677 def __init__(self, parent = None, **kw):
2678
2679 # Define the megawidget options.
2680
2681 optiondefs = (
2682 ('labelmargin', 0, INITOPT),
2683 ('labelpos', None, INITOPT),
2684 ('orient', 'horizontal', INITOPT),
2685 ('padx', 3, INITOPT),
2686 ('pady', 3, INITOPT),
2687 )
2688 self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',))
2689
2690 # Initialise the base class (after defining the options).
2691 MegaWidget.__init__(self, parent)
2692
2693 # Create the components.
2694 interior = self.interior()
2695 if self['labelpos'] is None:
2696 self._buttonBoxFrame = self._hull
2697 columnOrRow = 0
2698 else:
2699 self._buttonBoxFrame = self.createcomponent('frame',
2700 (), None,
2701 Tkinter.Frame, (interior,))
2702 self._buttonBoxFrame.grid(column=2, row=2, sticky='nsew')
2703 columnOrRow = 2
2704
2705 self.createlabel(interior)
2706
2707 orient = self['orient']
2708 if orient == 'horizontal':
2709 interior.grid_columnconfigure(columnOrRow, weight = 1)
2710 elif orient == 'vertical':
2711 interior.grid_rowconfigure(columnOrRow, weight = 1)
2712 else:
2713 raise ValueError('bad orient option ' + repr(orient) + \
2714 ': must be either \'horizontal\' or \'vertical\'')
2715
2716 # Initialise instance variables.
2717
2718 # List of tuples describing the buttons:
2719 # - name
2720 # - button widget
2721 self._buttonList = []
2722
2723 # The index of the default button.
2724 self._defaultButton = None
2725
2726 self._timerId = None
2727
2728 # Check keywords and initialise options.
2729 self.initialiseoptions()
2730
2731 def destroy(self):
2732 if self._timerId:
2733 self.after_cancel(self._timerId)
2734 self._timerId = None
2735 MegaWidget.destroy(self)
2736
2737 def numbuttons(self):
2738 return len(self._buttonList)
2739
2740 def index(self, index, forInsert = 0):
2741 listLength = len(self._buttonList)
2742 if isinstance(index, int):
2743 if forInsert and index <= listLength:
2744 return index
2745 elif not forInsert and index < listLength:
2746 return index
2747 else:
2748 raise ValueError('index "%s" is out of range' % index)
2749 elif index is END:
2750 if forInsert:
2751 return listLength
2752 elif listLength > 0:
2753 return listLength - 1
2754 else:
2755 raise ValueError('ButtonBox has no buttons')
2756 elif index is DEFAULT:
2757 if self._defaultButton is not None:
2758 return self._defaultButton
2759 raise ValueError('ButtonBox has no default')
2760 else:
2761 names = [t[0] for t in self._buttonList]
2762 if index in names:
2763 return names.index(index)
2764 validValues = 'a name, a number, END or DEFAULT'
2765 raise ValueError('bad index "%s": must be %s' % (index, validValues))
2766
2767 def insert(self, componentName, beforeComponent = 0, **kw):
2768 if componentName in self.components():
2769 raise ValueError('button "%s" already exists' % componentName)
2770 if 'text' not in kw:
2771 kw['text'] = componentName
2772 kw['default'] = 'normal'
2773 button = self.createcomponent(componentName,
2774 (), 'Button',
2775 Tkinter.Button, (self._buttonBoxFrame,), **kw)
2776
2777 index = self.index(beforeComponent, 1)
2778 horizontal = self['orient'] == 'horizontal'
2779 numButtons = len(self._buttonList)
2780
2781 # Shift buttons up one position.
2782 for i in range(numButtons - 1, index - 1, -1):
2783 widget = self._buttonList[i][1]
2784 pos = i * 2 + 3
2785 if horizontal:
2786 widget.grid(column = pos, row = 0)
2787 else:
2788 widget.grid(column = 0, row = pos)
2789
2790 # Display the new button.
2791 if horizontal:
2792 button.grid(column = index * 2 + 1, row = 0, sticky = 'ew',
2793 padx = self['padx'], pady = self['pady'])
2794 self._buttonBoxFrame.grid_columnconfigure(
2795 numButtons * 2 + 2, weight = 1)
2796 else:
2797 button.grid(column = 0, row = index * 2 + 1, sticky = 'ew',
2798 padx = self['padx'], pady = self['pady'])
2799 self._buttonBoxFrame.grid_rowconfigure(
2800 numButtons * 2 + 2, weight = 1)
2801 self._buttonList.insert(index, (componentName, button))
2802
2803 return button
2804
2805 def add(self, componentName, **kw):
2806 return self.insert(componentName, len(self._buttonList), **kw)
2807
2808 def delete(self, index):
2809 index = self.index(index)
2810 (name, widget) = self._buttonList[index]
2811 widget.grid_forget()
2812 self.destroycomponent(name)
2813
2814 numButtons = len(self._buttonList)
2815
2816 # Shift buttons down one position.
2817 horizontal = self['orient'] == 'horizontal'
2818 for i in range(index + 1, numButtons):
2819 widget = self._buttonList[i][1]
2820 pos = i * 2 - 1
2821 if horizontal:
2822 widget.grid(column = pos, row = 0)
2823 else:
2824 widget.grid(column = 0, row = pos)
2825
2826 if horizontal:
2827 self._buttonBoxFrame.grid_columnconfigure(numButtons * 2 - 1,
2828 minsize = 0)
2829 self._buttonBoxFrame.grid_columnconfigure(numButtons * 2, weight = 0)
2830 else:
2831 self._buttonBoxFrame.grid_rowconfigure(numButtons * 2, weight = 0)
2832 del self._buttonList[index]
2833
2834 def setdefault(self, index):
2835 # Turn off the default ring around the current default button.
2836 if self._defaultButton is not None:
2837 button = self._buttonList[self._defaultButton][1]
2838 button.configure(default = 'normal')
2839 self._defaultButton = None
2840
2841 # Turn on the default ring around the new default button.
2842 if index is not None:
2843 index = self.index(index)
2844 self._defaultButton = index
2845 button = self._buttonList[index][1]
2846 button.configure(default = 'active')
2847
2848 def invoke(self, index = DEFAULT, noFlash = 0):
2849 # Invoke the callback associated with the *index* button. If
2850 # *noFlash* is not set, flash the button to indicate to the
2851 # user that something happened.
2852
2853 button = self._buttonList[self.index(index)][1]
2854 if not noFlash:
2855 state = button.cget('state')
2856 relief = button.cget('relief')
2857 button.configure(state = 'active', relief = 'sunken')
2858 self.update_idletasks()
2859 self.after(100)
2860 button.configure(state = state, relief = relief)
2861 return button.invoke()
2862
2863 def button(self, buttonIndex):
2864 return self._buttonList[self.index(buttonIndex)][1]
2865
2866 def alignbuttons(self, when = 'later'):
2867 if when == 'later':
2868 if not self._timerId:
2869 self._timerId = self.after_idle(self.alignbuttons, 'now')
2870 return
2871 self.update_idletasks()
2872 self._timerId = None
2873
2874 # Determine the width of the maximum length button.
2875 max = 0
2876 horizontal = (self['orient'] == 'horizontal')
2877 for index in range(len(self._buttonList)):
2878 gridIndex = index * 2 + 1
2879 if horizontal:
2880 width = self._buttonBoxFrame.grid_bbox(gridIndex, 0)[2]
2881 else:
2882 width = self._buttonBoxFrame.grid_bbox(0, gridIndex)[2]
2883 if width > max:
2884 max = width
2885
2886 # Set the width of all the buttons to be the same.
2887 if horizontal:
2888 for index in range(len(self._buttonList)):
2889 self._buttonBoxFrame.grid_columnconfigure(index * 2 + 1,
2890 minsize = max)
2891 else:
2892 self._buttonBoxFrame.grid_columnconfigure(0, minsize = max)
2893
2894 ######################################################################
2895 ### File: PmwEntryField.py
2896 # Based on iwidgets2.2.0/entryfield.itk code.
2897
2898 import re
2899
2900
2901 # Possible return values of validation functions.
2902 OK = 1
2903 ERROR = 0
2904 PARTIAL = -1
2905
2906 class EntryField(MegaWidget):
2907 _classBindingsDefinedFor = 0
2908
2909 def __init__(self, parent = None, **kw):
2910
2911 # Define the megawidget options.
2912
2913 optiondefs = (
2914 ('command', None, None),
2915 ('errorbackground', 'pink', None),
2916 ('invalidcommand', self.bell, None),
2917 ('labelmargin', 0, INITOPT),
2918 ('labelpos', None, INITOPT),
2919 ('modifiedcommand', None, None),
2920 ('sticky', 'ew', INITOPT),
2921 ('validate', None, self._validate),
2922 ('extravalidators', {}, None),
2923 ('value', '', INITOPT),
2924 )
2925 self.defineoptions(kw, optiondefs)
2926
2927 # Initialise the base class (after defining the options).
2928 MegaWidget.__init__(self, parent)
2929
2930 # Create the components.
2931 interior = self.interior()
2932 self._entryFieldEntry = self.createcomponent('entry',
2933 (), None,
2934 Tkinter.Entry, (interior,))
2935 self._entryFieldEntry.grid(column=2, row=2, sticky=self['sticky'])
2936 if self['value'] != '':
2937 self.__setEntry(self['value'])
2938 interior.grid_columnconfigure(2, weight=1)
2939 interior.grid_rowconfigure(2, weight=1)
2940
2941 self.createlabel(interior)
2942
2943 # Initialise instance variables.
2944
2945 self.normalBackground = None
2946 self._previousText = None
2947
2948 # Initialise instance.
2949
2950 _registerEntryField(self._entryFieldEntry, self)
2951
2952 # Establish the special class bindings if not already done.
2953 # Also create bindings if the Tkinter default interpreter has
2954 # changed. Use Tkinter._default_root to create class
2955 # bindings, so that a reference to root is created by
2956 # bind_class rather than a reference to self, which would
2957 # prevent object cleanup.
2958 if EntryField._classBindingsDefinedFor != Tkinter._default_root:
2959 tagList = self._entryFieldEntry.bindtags()
2960 root = Tkinter._default_root
2961
2962 allSequences = {}
2963 for tag in tagList:
2964
2965 sequences = root.bind_class(tag)
2966 if isinstance(sequences, str):
2967 # In old versions of Tkinter, bind_class returns a string
2968 sequences = root.tk.splitlist(sequences)
2969
2970 for sequence in sequences:
2971 allSequences[sequence] = None
2972 for sequence in allSequences:
2973 root.bind_class('EntryFieldPre', sequence, _preProcess)
2974 root.bind_class('EntryFieldPost', sequence, _postProcess)
2975
2976 EntryField._classBindingsDefinedFor = root
2977
2978 self._entryFieldEntry.bindtags(('EntryFieldPre',) +
2979 self._entryFieldEntry.bindtags() + ('EntryFieldPost',))
2980 self._entryFieldEntry.bind('<Return>', self._executeCommand)
2981
2982 # Check keywords and initialise options.
2983 self.initialiseoptions()
2984
2985 def destroy(self):
2986 _deregisterEntryField(self._entryFieldEntry)
2987 MegaWidget.destroy(self)
2988
2989 def _getValidatorFunc(self, validator, index):
2990 # Search the extra and standard validator lists for the
2991 # given 'validator'. If 'validator' is an alias, then
2992 # continue the search using the alias. Make sure that
2993 # self-referencial aliases do not cause infinite loops.
2994
2995 extraValidators = self['extravalidators']
2996 traversedValidators = []
2997
2998 while 1:
2999 traversedValidators.append(validator)
3000 if validator in extraValidators:
3001 validator = extraValidators[validator][index]
3002 elif validator in _standardValidators:
3003 validator = _standardValidators[validator][index]
3004 else:
3005 return validator
3006 if validator in traversedValidators:
3007 return validator
3008
3009 def _validate(self):
3010 dct = {
3011 'validator' : None,
3012 'min' : None,
3013 'max' : None,
3014 'minstrict' : 1,
3015 'maxstrict' : 1,
3016 }
3017 opt = self['validate']
3018 if isinstance(opt, dict):
3019 dct.update(opt)
3020 else:
3021 dct['validator'] = opt
3022
3023 # Look up validator maps and replace 'validator' field with
3024 # the corresponding function.
3025 validator = dct['validator']
3026 valFunction = self._getValidatorFunc(validator, 0)
3027 self._checkValidateFunction(valFunction, 'validate', validator)
3028 dct['validator'] = valFunction
3029
3030 # Look up validator maps and replace 'stringtovalue' field
3031 # with the corresponding function.
3032 if 'stringtovalue' in dct:
3033 stringtovalue = dct['stringtovalue']
3034 strFunction = self._getValidatorFunc(stringtovalue, 1)
3035 self._checkValidateFunction(
3036 strFunction, 'stringtovalue', stringtovalue)
3037 else:
3038 strFunction = self._getValidatorFunc(validator, 1)
3039 if strFunction == validator:
3040 strFunction = len
3041 dct['stringtovalue'] = strFunction
3042
3043 self._validationInfo = dct
3044 args = dct.copy()
3045 del args['validator']
3046 del args['min']
3047 del args['max']
3048 del args['minstrict']
3049 del args['maxstrict']
3050 del args['stringtovalue']
3051 self._validationArgs = args
3052 self._previousText = None
3053
3054 if isinstance(dct['min'], str) and strFunction is not None:
3055 dct['min'] = strFunction(dct['min'], **args)
3056 if isinstance(dct['max'], str) and strFunction is not None:
3057 dct['max'] = strFunction(dct['max'], **args)
3058
3059 self._checkValidity()
3060
3061 def _checkValidateFunction(self, function, option, validator):
3062 # Raise an error if 'function' is not a function or None.
3063
3064 if function is not None and not hasattr(function, '__call__'):
3065 extraValidators = self['extravalidators']
3066 extra = list(extraValidators)
3067 extra.sort()
3068 extra = tuple(extra)
3069 standard = list(_standardValidators)
3070 standard.sort()
3071 standard = tuple(standard)
3072 msg = 'bad %s value "%s": must be a function or one of ' \
3073 'the standard validators %s or extra validators %s'
3074 raise ValueError(msg % (option, validator, standard, extra))
3075
3076 def _executeCommand(self, event = None):
3077 cmd = self['command']
3078 if hasattr(cmd, '__call__'):
3079 if event is None:
3080 # Return result of command for invoke() method.
3081 return cmd()
3082 else:
3083 cmd()
3084
3085 def _preProcess(self):
3086
3087 self._previousText = self._entryFieldEntry.get()
3088 self._previousICursor = self._entryFieldEntry.index('insert')
3089 self._previousXview = self._entryFieldEntry.index('@0')
3090 if self._entryFieldEntry.selection_present():
3091 self._previousSel= (self._entryFieldEntry.index('sel.first'),
3092 self._entryFieldEntry.index('sel.last'))
3093 else:
3094 self._previousSel = None
3095
3096 def _postProcess(self):
3097
3098 # No need to check if text has not changed.
3099 previousText = self._previousText
3100 if previousText == self._entryFieldEntry.get():
3101 return self.valid()
3102
3103 valid = self._checkValidity()
3104 if self.hulldestroyed():
3105 # The invalidcommand called by _checkValidity() destroyed us.
3106 return valid
3107
3108 cmd = self['modifiedcommand']
3109 if hasattr(cmd, '__call__') and previousText != self._entryFieldEntry.get():
3110 cmd()
3111 return valid
3112
3113 def checkentry(self):
3114 # If there is a variable specified by the entry_textvariable
3115 # option, checkentry() should be called after the set() method
3116 # of the variable is called.
3117
3118 self._previousText = None
3119 return self._postProcess()
3120
3121 def _getValidity(self):
3122 text = self._entryFieldEntry.get()
3123 dict = self._validationInfo
3124 args = self._validationArgs
3125
3126 if dict['validator'] is not None:
3127 status = dict['validator'](text, **args)
3128 if status != OK:
3129 return status
3130
3131 # Check for out of (min, max) range.
3132 if dict['stringtovalue'] is not None:
3133 min = dict['min']
3134 max = dict['max']
3135 if min is None and max is None:
3136 return OK
3137 val = dict['stringtovalue'](text, **args)
3138 if min is not None and val < min:
3139 if dict['minstrict']:
3140 return ERROR
3141 else:
3142 return PARTIAL
3143 if max is not None and val > max:
3144 if dict['maxstrict']:
3145 return ERROR
3146 else:
3147 return PARTIAL
3148 return OK
3149
3150 def _checkValidity(self):
3151 valid = self._getValidity()
3152 oldValidity = valid
3153
3154 if valid == ERROR:
3155 # The entry is invalid.
3156 cmd = self['invalidcommand']
3157 if hasattr(cmd, '__call__'):
3158 cmd()
3159 if self.hulldestroyed():
3160 # The invalidcommand destroyed us.
3161 return oldValidity
3162
3163 # Restore the entry to its previous value.
3164 if self._previousText is not None:
3165 self.__setEntry(self._previousText)
3166 self._entryFieldEntry.icursor(self._previousICursor)
3167 self._entryFieldEntry.xview(self._previousXview)
3168 if self._previousSel is not None:
3169 self._entryFieldEntry.selection_range(self._previousSel[0],
3170 self._previousSel[1])
3171
3172 # Check if the saved text is valid as well.
3173 valid = self._getValidity()
3174
3175 self._valid = valid
3176
3177 if self.hulldestroyed():
3178 # The validator or stringtovalue commands called by
3179 # _checkValidity() destroyed us.
3180 return oldValidity
3181
3182 if valid == OK:
3183 if self.normalBackground is not None:
3184 self._entryFieldEntry.configure(
3185 background = self.normalBackground)
3186 self.normalBackground = None
3187 else:
3188 if self.normalBackground is None:
3189 self.normalBackground = self._entryFieldEntry.cget('background')
3190 self._entryFieldEntry.configure(
3191 background = self['errorbackground'])
3192
3193 return oldValidity
3194
3195 def invoke(self):
3196 return self._executeCommand()
3197
3198 def valid(self):
3199 return self._valid == OK
3200
3201 def clear(self):
3202 self.setentry('')
3203
3204 def __setEntry(self, text):
3205 oldState = str(self._entryFieldEntry.cget('state'))
3206 if oldState != 'normal':
3207 self._entryFieldEntry.configure(state='normal')
3208 self._entryFieldEntry.delete(0, 'end')
3209 self._entryFieldEntry.insert(0, text)
3210 if oldState != 'normal':
3211 self._entryFieldEntry.configure(state=oldState)
3212
3213 def setentry(self, text):
3214 self._preProcess()
3215 self.__setEntry(text)
3216 return self._postProcess()
3217
3218 def getvalue(self):
3219 return self._entryFieldEntry.get()
3220
3221 def setvalue(self, text):
3222 return self.setentry(text)
3223
3224 forwardmethods(EntryField, Tkinter.Entry, '_entryFieldEntry')
3225
3226 # ======================================================================
3227
3228
3229 # Entry field validation functions
3230
3231 _numericregex = re.compile('^[0-9]*$')
3232 _alphabeticregex = re.compile('^[a-z]*$', re.IGNORECASE)
3233 _alphanumericregex = re.compile('^[0-9a-z]*$', re.IGNORECASE)
3234
3235 def numericvalidator(text):
3236 if text == '':
3237 return PARTIAL
3238 else:
3239 if _numericregex.match(text) is None:
3240 return ERROR
3241 else:
3242 return OK
3243
3244 def integervalidator(text):
3245 if text in ('', '-', '+'):
3246 return PARTIAL
3247 try:
3248 long(text)
3249 return OK
3250 except ValueError:
3251 return ERROR
3252
3253 def alphabeticvalidator(text):
3254 if _alphabeticregex.match(text) is None:
3255 return ERROR
3256 else:
3257 return OK
3258
3259 def alphanumericvalidator(text):
3260 if _alphanumericregex.match(text) is None:
3261 return ERROR
3262 else:
3263 return OK
3264
3265 def hexadecimalvalidator(text):
3266 if text in ('', '0x', '0X', '+', '+0x', '+0X', '-', '-0x', '-0X'):
3267 return PARTIAL
3268 try:
3269 long(text, 16)
3270 return OK
3271 except ValueError:
3272 return ERROR
3273
3274 def realvalidator(text, separator = '.'):
3275 if separator != '.':
3276 if text.find('.') >= 0:
3277 return ERROR
3278 index = text.find(separator)
3279 if index >= 0:
3280 text = text[:index] + '.' + text[index + 1:]
3281 try:
3282 float(text)
3283 return OK
3284 except ValueError:
3285 # Check if the string could be made valid by appending a digit
3286 # eg ('-', '+', '.', '-.', '+.', '1.23e', '1E-').
3287 if len(text) == 0:
3288 return PARTIAL
3289 if text[-1].isdigit():
3290 return ERROR
3291 try:
3292 float(text + '0')
3293 return PARTIAL
3294 except ValueError:
3295 return ERROR
3296
3297 def timevalidator(text, separator = ':'):
3298 try:
3299 timestringtoseconds(text, separator)
3300 return OK
3301 except ValueError:
3302 if len(text) > 0 and text[0] in ('+', '-'):
3303 text = text[1:]
3304 if re.search('[^0-9' + separator + ']', text) is not None:
3305 return ERROR
3306 return PARTIAL
3307
3308 def datevalidator(text, format = 'ymd', separator = '/'):
3309 try:
3310 datestringtojdn(text, format, separator)
3311 return OK
3312 except ValueError:
3313 if re.search('[^0-9' + separator + ']', text) is not None:
3314 return ERROR
3315 return PARTIAL
3316
3317 _standardValidators = {
3318 'numeric' : (numericvalidator, long),
3319 'integer' : (integervalidator, long),
3320 'hexadecimal' : (hexadecimalvalidator, lambda s: long(s, 16)),
3321 'real' : (realvalidator, stringtoreal),
3322 'alphabetic' : (alphabeticvalidator, len),
3323 'alphanumeric' : (alphanumericvalidator, len),
3324 'time' : (timevalidator, timestringtoseconds),
3325 'date' : (datevalidator, datestringtojdn),
3326 }
3327
3328 _entryCache = {}
3329
3330 def _registerEntryField(entry, entryField):
3331 # Register an EntryField widget for an Entry widget
3332
3333 _entryCache[entry] = entryField
3334
3335 def _deregisterEntryField(entry):
3336 # Deregister an Entry widget
3337 del _entryCache[entry]
3338
3339 def _preProcess(event):
3340 # Forward preprocess events for an Entry to it's EntryField
3341
3342 if event.widget in _entryCache:
3343 _entryCache[event.widget]._preProcess()
3344
3345 def _postProcess(event):
3346 # Forward postprocess events for an Entry to it's EntryField
3347
3348 # The function specified by the 'command' option may have destroyed
3349 # the megawidget in a binding earlier in bindtags, so need to check.
3350 if event.widget in _entryCache:
3351 _entryCache[event.widget]._postProcess()
3352
3353 ######################################################################
3354 ### File: PmwGroup.py
3355
3356
3357 def aligngrouptags(groups):
3358 # Adjust the y position of the tags in /groups/ so that they all
3359 # have the height of the highest tag.
3360
3361 maxTagHeight = 0
3362 for group in groups:
3363 if group._tag is None:
3364 height = (int(str(group._ring.cget('borderwidth'))) +
3365 int(str(group._ring.cget('highlightthickness'))))
3366 else:
3367 height = group._tag.winfo_reqheight()
3368 if maxTagHeight < height:
3369 maxTagHeight = height
3370
3371 for group in groups:
3372 ringBorder = (int(str(group._ring.cget('borderwidth'))) +
3373 int(str(group._ring.cget('highlightthickness'))))
3374 topBorder = maxTagHeight / 2 - ringBorder / 2
3375 group._hull.grid_rowconfigure(0, minsize = topBorder)
3376 group._ring.grid_rowconfigure(0,
3377 minsize = maxTagHeight - topBorder - ringBorder)
3378 if group._tag is not None:
3379 group._tag.place(y = maxTagHeight / 2)
3380
3381 class Group( MegaWidget ):
3382 def __init__(self, parent = None, **kw):
3383
3384 # Define the megawidget options.
3385
3386 optiondefs = (
3387 ('collapsedsize', 6, INITOPT),
3388 ('ring_borderwidth', 2, None),
3389 ('ring_relief', 'groove', None),
3390 ('tagindent', 10, INITOPT),
3391 )
3392 self.defineoptions(kw, optiondefs)
3393
3394 # Initialise the base class (after defining the options).
3395 MegaWidget.__init__(self, parent)
3396
3397 # Create the components.
3398 interior = MegaWidget.interior(self)
3399
3400 self._ring = self.createcomponent(
3401 'ring',
3402 (), None,
3403 Tkinter.Frame, (interior,),
3404 )
3405
3406 self._groupChildSite = self.createcomponent(
3407 'groupchildsite',
3408 (), None,
3409 Tkinter.Frame, (self._ring,)
3410 )
3411
3412 self._tag = self.createcomponent(
3413 'tag',
3414 (), None,
3415 Tkinter.Label, (interior,),
3416 )
3417
3418 ringBorder = (int(str(self._ring.cget('borderwidth'))) +
3419 int(str(self._ring.cget('highlightthickness'))))
3420 if self._tag is None:
3421 tagHeight = ringBorder
3422 else:
3423 tagHeight = self._tag.winfo_reqheight()
3424 self._tag.place(
3425 x = ringBorder + self['tagindent'],
3426 y = tagHeight / 2,
3427 anchor = 'w')
3428
3429 topBorder = tagHeight / 2 - ringBorder / 2
3430 self._ring.grid(column = 0, row = 1, sticky = 'nsew')
3431 interior.grid_columnconfigure(0, weight = 1)
3432 interior.grid_rowconfigure(1, weight = 1)
3433 interior.grid_rowconfigure(0, minsize = topBorder)
3434
3435 self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew')
3436 self._ring.grid_columnconfigure(0, weight = 1)
3437 self._ring.grid_rowconfigure(1, weight = 1)
3438 self._ring.grid_rowconfigure(0,
3439 minsize = tagHeight - topBorder - ringBorder)
3440
3441 self.showing = 1
3442
3443 # Check keywords and initialise options.
3444 self.initialiseoptions()
3445
3446 def toggle(self):
3447 if self.showing:
3448 self.collapse()
3449 else:
3450 self.expand()
3451 self.showing = not self.showing
3452
3453 def expand(self):
3454 self._groupChildSite.grid(column = 0, row = 1, sticky = 'nsew')
3455
3456 def collapse(self):
3457 self._groupChildSite.grid_forget()
3458 if self._tag is None:
3459 tagHeight = 0
3460 else:
3461 tagHeight = self._tag.winfo_reqheight()
3462 self._ring.configure(height=(tagHeight / 2) + self['collapsedsize'])
3463
3464 def interior(self):
3465 return self._groupChildSite
3466
3467 ######################################################################
3468 ### File: PmwLabeledWidget.py
3469
3470
3471 class LabeledWidget(MegaWidget):
3472 def __init__(self, parent = None, **kw):
3473
3474 # Define the megawidget options.
3475
3476 optiondefs = (
3477 ('labelmargin', 0, INITOPT),
3478 ('labelpos', None, INITOPT),
3479 ('sticky', 'nsew', INITOPT),
3480 )
3481 self.defineoptions(kw, optiondefs)
3482
3483 # Initialise the base class (after defining the options).
3484 MegaWidget.__init__(self, parent)
3485
3486 # Create the components.
3487 interior = MegaWidget.interior(self)
3488 self._labelChildSite = self.createcomponent('labelchildsite',
3489 (), None,
3490 Tkinter.Frame, (interior,))
3491 self._labelChildSite.grid(column=2, row=2, sticky=self['sticky'])
3492 interior.grid_columnconfigure(2, weight=1)
3493 interior.grid_rowconfigure(2, weight=1)
3494
3495 self.createlabel(interior)
3496
3497 # Check keywords and initialise options.
3498 self.initialiseoptions()
3499
3500 def interior(self):
3501 return self._labelChildSite
3502
3503 ######################################################################
3504 ### File: PmwMainMenuBar.py
3505 # Main menubar
3506
3507
3508
3509 class MainMenuBar(MegaArchetype):
3510
3511 def __init__(self, parent = None, **kw):
3512
3513 # Define the megawidget options.
3514
3515 optiondefs = (
3516 ('balloon', None, None),
3517 ('hotkeys', 1, INITOPT),
3518 ('hull_tearoff', 0, None),
3519 )
3520 self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu',))
3521
3522 # Initialise the base class (after defining the options).
3523 MegaArchetype.__init__(self, parent, Tkinter.Menu)
3524
3525 self._menuInfo = {}
3526 self._menuInfo[None] = (None, [])
3527 # Map from a menu name to a tuple of information about the menu.
3528 # The first item in the tuple is the name of the parent menu (for
3529 # toplevel menus this is None). The second item in the tuple is
3530 # a list of status help messages for each item in the menu.
3531 # The key for the information for the main menubar is None.
3532
3533 self._menu = self.interior()
3534 self._menu.bind('<Leave>', self._resetHelpmessage)
3535 self._menu.bind('<Motion>',
3536 lambda event=None, self=self: self._menuHelp(event, None))
3537
3538 # Check keywords and initialise options.
3539 self.initialiseoptions()
3540
3541 def deletemenuitems(self, menuName, start, end = None):
3542 self.component(menuName).delete(start, end)
3543 if end is None:
3544 del self._menuInfo[menuName][1][start]
3545 else:
3546 self._menuInfo[menuName][1][start:end+1] = []
3547
3548 def deletemenu(self, menuName):
3549 """Delete should be called for cascaded menus before main menus.
3550 """
3551
3552 parentName = self._menuInfo[menuName][0]
3553 del self._menuInfo[menuName]
3554 if parentName is None:
3555 parentMenu = self._menu
3556 else:
3557 parentMenu = self.component(parentName)
3558
3559 menu = self.component(menuName)
3560 menuId = str(menu)
3561 for item in range(parentMenu.index('end') + 1):
3562 if parentMenu.type(item) == 'cascade':
3563 itemMenu = str(parentMenu.entrycget(item, 'menu'))
3564 if itemMenu == menuId:
3565 parentMenu.delete(item)
3566 del self._menuInfo[parentName][1][item]
3567 break
3568
3569 self.destroycomponent(menuName)
3570
3571 def disableall(self):
3572 for index in range(len(self._menuInfo[None][1])):
3573 self.entryconfigure(index, state = 'disabled')
3574
3575 def enableall(self):
3576 for index in range(len(self._menuInfo[None][1])):
3577 self.entryconfigure(index, state = 'normal')
3578
3579 def addmenu(self, menuName, balloonHelp, statusHelp = None,
3580 traverseSpec = None, **kw):
3581 if statusHelp is None:
3582 statusHelp = balloonHelp
3583 self._addmenu(None, menuName, balloonHelp, statusHelp,
3584 traverseSpec, kw)
3585
3586 def addcascademenu(self, parentMenuName, menuName, statusHelp='',
3587 traverseSpec = None, **kw):
3588 self._addmenu(parentMenuName, menuName, None, statusHelp,
3589 traverseSpec, kw)
3590
3591 def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp,
3592 traverseSpec, kw):
3593
3594 if (menuName) in self.components():
3595 raise ValueError('menu "%s" already exists' % menuName)
3596
3597 menukw = {}
3598 if 'tearoff' in kw:
3599 menukw['tearoff'] = kw['tearoff']
3600 del kw['tearoff']
3601 else:
3602 menukw['tearoff'] = 0
3603 if 'name' in kw:
3604 menukw['name'] = kw['name']
3605 del kw['name']
3606
3607 if 'label' not in kw:
3608 kw['label'] = menuName
3609
3610 self._addHotkeyToOptions(parentMenuName, kw, traverseSpec)
3611
3612 if parentMenuName is None:
3613 parentMenu = self._menu
3614 balloon = self['balloon']
3615 # Bug in Tk: balloon help not implemented
3616 # if balloon is not None:
3617 # balloon.mainmenubind(parentMenu, balloonHelp, statusHelp)
3618 else:
3619 parentMenu = self.component(parentMenuName)
3620
3621 parentMenu.add_cascade(**kw)
3622
3623 menu = self.createcomponent(menuName,
3624 (), 'Menu',
3625 Tkinter.Menu, (parentMenu,), **menukw)
3626 parentMenu.entryconfigure('end', menu = menu)
3627
3628 self._menuInfo[parentMenuName][1].append(statusHelp)
3629 self._menuInfo[menuName] = (parentMenuName, [])
3630
3631 menu.bind('<Leave>', self._resetHelpmessage)
3632 menu.bind('<Motion>',
3633 lambda event=None, self=self, menuName=menuName:
3634 self._menuHelp(event, menuName))
3635
3636 def addmenuitem(self, menuName, itemType, statusHelp = '',
3637 traverseSpec = None, **kw):
3638
3639 menu = self.component(menuName)
3640 if itemType != 'separator':
3641 self._addHotkeyToOptions(menuName, kw, traverseSpec)
3642
3643 if itemType == 'command':
3644 command = menu.add_command
3645 elif itemType == 'separator':
3646 command = menu.add_separator
3647 elif itemType == 'checkbutton':
3648 command = menu.add_checkbutton
3649 elif itemType == 'radiobutton':
3650 command = menu.add_radiobutton
3651 elif itemType == 'cascade':
3652 command = menu.add_cascade
3653 else:
3654 raise ValueError('unknown menuitem type "%s"' % itemType)
3655
3656 self._menuInfo[menuName][1].append(statusHelp)
3657 command(**kw)
3658
3659 def _addHotkeyToOptions(self, menuName, kw, traverseSpec):
3660
3661 if (not self['hotkeys'] or 'underline' in kw or
3662 'label' not in kw):
3663 return
3664
3665 if isinstance(traverseSpec, int):
3666 kw['underline'] = traverseSpec
3667 return
3668
3669 if menuName is None:
3670 menu = self._menu
3671 else:
3672 menu = self.component(menuName)
3673 hotkeyList = []
3674 end = menu.index('end')
3675 if end is not None:
3676 for item in range(end + 1):
3677 if menu.type(item) not in ('separator', 'tearoff'):
3678 underline = \
3679 int(str(menu.entrycget(item, 'underline')))
3680 if underline != -1:
3681 label = str(menu.entrycget(item, 'label'))
3682 if underline < len(label):
3683 hotkey = label[underline].lower()
3684 if hotkey not in hotkeyList:
3685 hotkeyList.append(hotkey)
3686
3687 name = kw['label']
3688
3689 if isinstance(traverseSpec, str):
3690 lowerLetter = traverseSpec.lower()
3691 if traverseSpec in name and lowerLetter not in hotkeyList:
3692 kw['underline'] = name.index(traverseSpec)
3693 else:
3694 lowerName = name.lower()
3695 for letter_index in range(len(name)):
3696 letter = lowerName[letter_index]
3697 if letter.isalnum() and letter not in hotkeyList:
3698 kw['underline'] = letter_index
3699 break
3700
3701 def _menuHelp(self, event, menuName):
3702 if menuName is None:
3703 menu = self._menu
3704 index = menu.index('@%d'% event.x)
3705 else:
3706 menu = self.component(menuName)
3707 index = menu.index('@%d'% event.y)
3708
3709 balloon = self['balloon']
3710 if balloon is not None:
3711 if index is None:
3712 balloon.showstatus('')
3713 else:
3714 if str(menu.cget('tearoff')) == '1':
3715 index = index - 1
3716 if index >= 0:
3717 help = self._menuInfo[menuName][1][index]
3718 balloon.showstatus(help)
3719
3720 def _resetHelpmessage(self, event=None):
3721 balloon = self['balloon']
3722 if balloon is not None:
3723 balloon.clearstatus()
3724
3725 forwardmethods(MainMenuBar, Tkinter.Menu, '_hull')
3726
3727 ######################################################################
3728 ### File: PmwMenuBar.py
3729 # Manager widget for menus.
3730
3731
3732
3733 class MenuBar(MegaWidget):
3734
3735 def __init__(self, parent = None, **kw):
3736
3737 # Define the megawidget options.
3738
3739 optiondefs = (
3740 ('balloon', None, None),
3741 ('hotkeys', 1, INITOPT),
3742 ('padx', 0, INITOPT),
3743 )
3744 self.defineoptions(kw, optiondefs, dynamicGroups = ('Menu', 'Button'))
3745
3746 # Initialise the base class (after defining the options).
3747 MegaWidget.__init__(self, parent)
3748
3749 self._menuInfo = {}
3750 # Map from a menu name to a tuple of information about the menu.
3751 # The first item in the tuple is the name of the parent menu (for
3752 # toplevel menus this is None). The second item in the tuple is
3753 # a list of status help messages for each item in the menu.
3754 # The third item in the tuple is the id of the binding used
3755 # to detect mouse motion to display status help.
3756 # Information for the toplevel menubuttons is not stored here.
3757
3758 self._mydeletecommand = self.component('hull').tk.deletecommand
3759 # Cache this method for use later.
3760
3761 # Check keywords and initialise options.
3762 self.initialiseoptions()
3763
3764 def deletemenuitems(self, menuName, start, end = None):
3765 self.component(menuName + '-menu').delete(start, end)
3766 if end is None:
3767 del self._menuInfo[menuName][1][start]
3768 else:
3769 self._menuInfo[menuName][1][start:end+1] = []
3770
3771 def deletemenu(self, menuName):
3772 """Delete should be called for cascaded menus before main menus.
3773 """
3774
3775 # Clean up binding for this menu.
3776 parentName = self._menuInfo[menuName][0]
3777 bindId = self._menuInfo[menuName][2]
3778 _bindtag = 'PmwMenuBar' + str(self) + menuName
3779 self.unbind_class(_bindtag, '<Motion>')
3780 self._mydeletecommand(bindId) # unbind_class does not clean up
3781 del self._menuInfo[menuName]
3782
3783 if parentName is None:
3784 self.destroycomponent(menuName + '-button')
3785 else:
3786 parentMenu = self.component(parentName + '-menu')
3787
3788 menu = self.component(menuName + '-menu')
3789 menuId = str(menu)
3790 for item in range(parentMenu.index('end') + 1):
3791 if parentMenu.type(item) == 'cascade':
3792 itemMenu = str(parentMenu.entrycget(item, 'menu'))
3793 if itemMenu == menuId:
3794 parentMenu.delete(item)
3795 del self._menuInfo[parentName][1][item]
3796 break
3797
3798 self.destroycomponent(menuName + '-menu')
3799
3800 def disableall(self):
3801 for menuName in self._menuInfo:
3802 if self._menuInfo[menuName][0] is None:
3803 menubutton = self.component(menuName + '-button')
3804 menubutton.configure(state = 'disabled')
3805
3806 def enableall(self):
3807 for menuName in self._menuInfo:
3808 if self._menuInfo[menuName][0] is None:
3809 menubutton = self.component(menuName + '-button')
3810 menubutton.configure(state = 'normal')
3811
3812 def addmenu(self, menuName, balloonHelp, statusHelp = None,
3813 side = 'left', traverseSpec = None, **kw):
3814
3815 self._addmenu(None, menuName, balloonHelp, statusHelp,
3816 traverseSpec, side, 'text', kw)
3817
3818 def addcascademenu(self, parentMenuName, menuName, statusHelp = '',
3819 traverseSpec = None, **kw):
3820
3821 self._addmenu(parentMenuName, menuName, None, statusHelp,
3822 traverseSpec, None, 'label', kw)
3823
3824 def _addmenu(self, parentMenuName, menuName, balloonHelp, statusHelp,
3825 traverseSpec, side, textKey, kw):
3826
3827 if (menuName + '-menu') in self.components():
3828 raise ValueError('menu "%s" already exists' % menuName)
3829
3830 menukw = {}
3831 if 'tearoff' in kw:
3832 menukw['tearoff'] = kw['tearoff']
3833 del kw['tearoff']
3834 else:
3835 menukw['tearoff'] = 0
3836
3837 if textKey not in kw:
3838 kw[textKey] = menuName
3839
3840 self._addHotkeyToOptions(parentMenuName, kw, textKey, traverseSpec)
3841
3842 if parentMenuName is None:
3843 button = self.createcomponent(menuName + '-button',
3844 (), 'Button',
3845 Tkinter.Menubutton, (self.interior(),), **kw)
3846 button.pack(side=side, padx = self['padx'])
3847 balloon = self['balloon']
3848 if balloon is not None:
3849 balloon.bind(button, balloonHelp, statusHelp)
3850 parentMenu = button
3851 else:
3852 parentMenu = self.component(parentMenuName + '-menu')
3853 parentMenu.add_cascade(**kw)
3854 self._menuInfo[parentMenuName][1].append(statusHelp)
3855
3856 menu = self.createcomponent(menuName + '-menu',
3857 (), 'Menu',
3858 Tkinter.Menu, (parentMenu,), **menukw)
3859 if parentMenuName is None:
3860 button.configure(menu = menu)
3861 else:
3862 parentMenu.entryconfigure('end', menu = menu)
3863
3864 # Need to put this binding after the class bindings so that
3865 # menu.index() does not lag behind.
3866 _bindtag = 'PmwMenuBar' + str(self) + menuName
3867 bindId = self.bind_class(_bindtag, '<Motion>',
3868 lambda event=None, self=self, menuName=menuName:
3869 self._menuHelp(menuName))
3870 menu.bindtags(menu.bindtags() + (_bindtag,))
3871 menu.bind('<Leave>', self._resetHelpmessage)
3872
3873 self._menuInfo[menuName] = (parentMenuName, [], bindId)
3874
3875 def addmenuitem(self, menuName, itemType, statusHelp = '',
3876 traverseSpec = None, **kw):
3877
3878 menu = self.component(menuName + '-menu')
3879 if itemType != 'separator':
3880 self._addHotkeyToOptions(menuName, kw, 'label', traverseSpec)
3881
3882 if itemType == 'command':
3883 command = menu.add_command
3884 elif itemType == 'separator':
3885 command = menu.add_separator
3886 elif itemType == 'checkbutton':
3887 command = menu.add_checkbutton
3888 elif itemType == 'radiobutton':
3889 command = menu.add_radiobutton
3890 elif itemType == 'cascade':
3891 command = menu.add_cascade
3892 else:
3893 raise ValueError('unknown menuitem type "%s"' % itemType)
3894
3895 self._menuInfo[menuName][1].append(statusHelp)
3896 command(**kw)
3897
3898 def _addHotkeyToOptions(self, menuName, kw, textKey, traverseSpec):
3899
3900 if (not self['hotkeys'] or 'underline' in kw or
3901 textKey not in kw):
3902 return
3903
3904 if isinstance(traverseSpec, int):
3905 kw['underline'] = traverseSpec
3906 return
3907
3908 hotkeyList = []
3909 if menuName is None:
3910 for menuName in self._menuInfo:
3911 if self._menuInfo[menuName][0] is None:
3912 menubutton = self.component(menuName + '-button')
3913 underline = int(str(menubutton.cget('underline')))
3914 if underline != -1:
3915 label = str(menubutton.cget(textKey))
3916 if underline < len(label):
3917 hotkey = label[underline].lower()
3918 if hotkey not in hotkeyList:
3919 hotkeyList.append(hotkey)
3920 else:
3921 menu = self.component(menuName + '-menu')
3922 end = menu.index('end')
3923 if end is not None:
3924 for item in range(end + 1):
3925 if menu.type(item) not in ('separator', 'tearoff'):
3926 underline = int(
3927 str(menu.entrycget(item, 'underline')))
3928 if underline != -1:
3929 label = str(menu.entrycget(item, textKey))
3930 if underline < len(label):
3931 hotkey = label[underline].lower()
3932 if hotkey not in hotkeyList:
3933 hotkeyList.append(hotkey)
3934
3935 name = kw[textKey]
3936
3937 if isinstance(traverseSpec, str):
3938 lowerLetter = traverseSpec.lower()
3939 if traverseSpec in name and lowerLetter not in hotkeyList:
3940 kw['underline'] = name.index(traverseSpec)
3941 else:
3942 lowerName = name.lower()
3943 for letter_index in range(len(name)):
3944 letter = lowerName[letter_index]
3945 if letter.isalnum() and letter not in hotkeyList:
3946 kw['underline'] = letter_index
3947 break
3948
3949 def _menuHelp(self, menuName):
3950 menu = self.component(menuName + '-menu')
3951 index = menu.index('active')
3952
3953 balloon = self['balloon']
3954 if balloon is not None:
3955 if index is None:
3956 balloon.showstatus('')
3957 else:
3958 if str(menu.cget('tearoff')) == '1':
3959 index = index - 1
3960 if index >= 0:
3961 help = self._menuInfo[menuName][1][index]
3962 balloon.showstatus(help)
3963
3964 def _resetHelpmessage(self, event=None):
3965 balloon = self['balloon']
3966 if balloon is not None:
3967 balloon.clearstatus()
3968
3969 ######################################################################
3970 ### File: PmwMessageBar.py
3971 # Class to display messages in an information line.
3972
3973
3974
3975 class MessageBar(MegaWidget):
3976 def __init__(self, parent = None, **kw):
3977
3978 # Define the megawidget options.
3979
3980 defaultMessageTypes = {
3981 # (priority, showtime, bells, logmessage)
3982 'systemerror' : (5, 10, 2, 1),
3983 'usererror' : (4, 5, 1, 0),
3984 'busy' : (3, 0, 0, 0),
3985 'systemevent' : (2, 5, 0, 0),
3986 'userevent' : (2, 5, 0, 0),
3987 'help' : (1, 5, 0, 0),
3988 'state' : (0, 0, 0, 0),
3989 }
3990 optiondefs = (
3991 ('labelmargin', 0, INITOPT),
3992 ('labelpos', None, INITOPT),
3993 ('messagetypes', defaultMessageTypes, INITOPT),
3994 ('silent', 0, None),
3995 ('sticky', 'ew', INITOPT),
3996 )
3997 self.defineoptions(kw, optiondefs)
3998
3999 # Initialise the base class (after defining the options).
4000 MegaWidget.__init__(self, parent)
4001
4002 # Create the components.
4003 interior = self.interior()
4004 self._messageBarEntry = self.createcomponent('entry',
4005 (), None,
4006 Tkinter.Entry, (interior,))
4007
4008 # Can't always use 'disabled', since this greys out text in Tk 8.4.2
4009 try:
4010 self._messageBarEntry.configure(state = 'readonly')
4011 except Tkinter.TclError:
4012 self._messageBarEntry.configure(state = 'disabled')
4013
4014 self._messageBarEntry.grid(column=2, row=2, sticky=self['sticky'])
4015 interior.grid_columnconfigure(2, weight=1)
4016 interior.grid_rowconfigure(2, weight=1)
4017
4018 self.createlabel(interior)
4019
4020 # Initialise instance variables.
4021 self._numPriorities = 0
4022 for info in self['messagetypes'].values():
4023 if self._numPriorities < info[0]:
4024 self._numPriorities = info[0]
4025
4026 self._numPriorities = self._numPriorities + 1
4027 self._timer = [None] * self._numPriorities
4028 self._messagetext = [''] * self._numPriorities
4029 self._activemessage = [0] * self._numPriorities
4030
4031 # Check keywords and initialise options.
4032 self.initialiseoptions()
4033
4034 def destroy(self):
4035 for timerId in self._timer:
4036 if timerId is not None:
4037 self.after_cancel(timerId)
4038 self._timer = [None] * self._numPriorities
4039 MegaWidget.destroy(self)
4040
4041 def message(self, type, text):
4042 # Display a message in the message bar.
4043
4044 (priority, showtime, bells, logmessage) = self['messagetypes'][type]
4045
4046 if not self['silent']:
4047 for i in range(bells):
4048 if i != 0:
4049 self.after(100)
4050 self.bell()
4051
4052 self._activemessage[priority] = 1
4053 if text is None:
4054 text = ''
4055 self._messagetext[priority] = text.replace('\n', ' ')
4056 self._redisplayInfoMessage()
4057
4058 if logmessage:
4059 # Should log this text to a text widget.
4060 pass
4061
4062 if showtime > 0:
4063 if self._timer[priority] is not None:
4064 self.after_cancel(self._timer[priority])
4065
4066 # Define a callback to clear this message after a time.
4067 def _clearmessage(self=self, priority=priority):
4068 self._clearActivemessage(priority)
4069
4070 mseconds = int(showtime * 1000)
4071 self._timer[priority] = self.after(mseconds, _clearmessage)
4072
4073 def helpmessage(self, text):
4074 if text is None:
4075 self.resetmessages('help')
4076 else:
4077 self.message('help', text)
4078
4079 def resetmessages(self, type):
4080 priority = self['messagetypes'][type][0]
4081 self._clearActivemessage(priority)
4082 for messagetype, info in self['messagetypes'].items():
4083 thisPriority = info[0]
4084 showtime = info[1]
4085 if thisPriority < priority and showtime != 0:
4086 self._clearActivemessage(thisPriority)
4087
4088 def _clearActivemessage(self, priority):
4089 self._activemessage[priority] = 0
4090 if self._timer[priority] is not None:
4091 self.after_cancel(self._timer[priority])
4092 self._timer[priority] = None
4093 self._redisplayInfoMessage()
4094
4095 def _redisplayInfoMessage(self):
4096 text = ''
4097 for priority in range(self._numPriorities - 1, -1, -1):
4098 if self._activemessage[priority]:
4099 text = self._messagetext[priority]
4100 break
4101 self._messageBarEntry.configure(state = 'normal')
4102 self._messageBarEntry.delete(0, 'end')
4103 self._messageBarEntry.insert('end', text)
4104
4105 # Can't always use 'disabled', since this greys out text in Tk 8.4.2
4106 try:
4107 self._messageBarEntry.configure(state = 'readonly')
4108 except Tkinter.TclError:
4109 self._messageBarEntry.configure(state = 'disabled')
4110
4111 forwardmethods(MessageBar, Tkinter.Entry, '_messageBarEntry')
4112
4113 ######################################################################
4114 ### File: PmwMessageDialog.py
4115 # Based on iwidgets2.2.0/messagedialog.itk code.
4116
4117
4118
4119 class MessageDialog(Dialog):
4120 def __init__(self, parent = None, **kw):
4121
4122 # Define the megawidget options.
4123
4124 optiondefs = (
4125 ('borderx', 20, INITOPT),
4126 ('bordery', 20, INITOPT),
4127 ('iconmargin', 20, INITOPT),
4128 ('iconpos', None, INITOPT),
4129 )
4130 self.defineoptions(kw, optiondefs)
4131
4132 # Initialise the base class (after defining the options).
4133 Dialog.__init__(self, parent)
4134
4135 # Create the components.
4136 interior = self.interior()
4137
4138 self._message = self.createcomponent('message',
4139 (), None,
4140 Tkinter.Label, (interior,))
4141
4142 iconpos = self['iconpos']
4143 iconmargin = self['iconmargin']
4144 borderx = self['borderx']
4145 bordery = self['bordery']
4146 border_right = 2
4147 border_bottom = 2
4148 if iconpos is None:
4149 self._message.grid(column = 1, row = 1)
4150 else:
4151 self._icon = self.createcomponent('icon',
4152 (), None,
4153 Tkinter.Label, (interior,))
4154 if iconpos not in 'nsew':
4155 raise ValueError('bad iconpos option "%s": should be n, s, e, or w' \
4156 % iconpos)
4157
4158 if iconpos in 'nw':
4159 icon = 1
4160 message = 3
4161 else:
4162 icon = 3
4163 message = 1
4164
4165 if iconpos in 'ns':
4166 # vertical layout
4167 self._icon.grid(column = 1, row = icon)
4168 self._message.grid(column = 1, row = message)
4169 interior.grid_rowconfigure(2, minsize = iconmargin)
4170 border_bottom = 4
4171 else:
4172 # horizontal layout
4173 self._icon.grid(column = icon, row = 1)
4174 self._message.grid(column = message, row = 1)
4175 interior.grid_columnconfigure(2, minsize = iconmargin)
4176 border_right = 4
4177
4178 interior.grid_columnconfigure(0, minsize = borderx)
4179 interior.grid_rowconfigure(0, minsize = bordery)
4180 interior.grid_columnconfigure(border_right, minsize = borderx)
4181 interior.grid_rowconfigure(border_bottom, minsize = bordery)
4182
4183
4184 # Check keywords and initialise options.
4185 self.initialiseoptions()
4186
4187 ######################################################################
4188 ### File: PmwNoteBook.py
4189
4190
4191 class NoteBook(MegaArchetype):
4192
4193 def __init__(self, parent = None, **kw):
4194
4195 # Define the megawidget options.
4196
4197 optiondefs = (
4198 ('hull_highlightthickness', 0, None),
4199 ('hull_borderwidth', 0, None),
4200 ('arrownavigation', 1, INITOPT),
4201 ('borderwidth', 2, INITOPT),
4202 ('createcommand', None, None),
4203 ('lowercommand', None, None),
4204 ('pagemargin', 4, INITOPT),
4205 ('raisecommand', None, None),
4206 ('tabpos', 'n', INITOPT),
4207 )
4208 self.defineoptions(kw, optiondefs, dynamicGroups = ('Page', 'Tab'))
4209
4210 # Initialise the base class (after defining the options).
4211 MegaArchetype.__init__(self, parent, Tkinter.Canvas)
4212
4213 self.bind('<Map>', self._handleMap)
4214 self.bind('<Configure>', self._handleConfigure)
4215
4216 tabpos = self['tabpos']
4217 if tabpos is not None and tabpos != 'n':
4218 raise ValueError('bad tabpos option %s: should be n or None' % repr(tabpos))
4219 self._withTabs = (tabpos is not None)
4220 self._pageMargin = self['pagemargin']
4221 self._borderWidth = self['borderwidth']
4222
4223 # Use a dictionary as a set of bits indicating what needs to
4224 # be redisplayed the next time _layout() is called. If
4225 # dictionary contains 'topPage' key, the value is the new top
4226 # page to be displayed. None indicates that all pages have
4227 # been deleted and that _layout() should draw a border under where
4228 # the tabs should be.
4229 self._pending = {}
4230 self._pending['size'] = 1
4231 self._pending['borderColor'] = 1
4232 self._pending['topPage'] = None
4233 if self._withTabs:
4234 self._pending['tabs'] = 1
4235
4236 self._canvasSize = None # This gets set by <Configure> events
4237
4238 # Set initial height of space for tabs
4239 if self._withTabs:
4240 self.tabBottom = 35
4241 else:
4242 self.tabBottom = 0
4243
4244 self._lightBorderColor, self._darkBorderColor = \
4245 Color.bordercolors(self, self['hull_background'])
4246
4247 self._pageNames = [] # List of page names
4248
4249 # Map from page name to page info. Each item is itself a
4250 # dictionary containing the following items:
4251 # page the Tkinter.Frame widget for the page
4252 # created set to true the first time the page is raised
4253 # tabbutton the Tkinter.Button widget for the button (if any)
4254 # tabreqwidth requested width of the tab
4255 # tabreqheight requested height of the tab
4256 # tabitems the canvas items for the button: the button
4257 # window item, the lightshadow and the darkshadow
4258 # left the left and right canvas coordinates of the tab
4259 # right
4260 self._pageAttrs = {}
4261
4262 # Name of page currently on top (actually displayed, using
4263 # create_window, not pending). Ignored if current top page
4264 # has been deleted or new top page is pending. None indicates
4265 # no pages in notebook.
4266 self._topPageName = None
4267
4268 # Canvas items used:
4269 # Per tab:
4270 # top and left shadow
4271 # right shadow
4272 # button
4273 # Per notebook:
4274 # page
4275 # top page
4276 # left shadow
4277 # bottom and right shadow
4278 # top (one or two items)
4279
4280 # Canvas tags used:
4281 # lighttag - top and left shadows of tabs and page
4282 # darktag - bottom and right shadows of tabs and page
4283 # (if no tabs then these are reversed)
4284 # (used to color the borders by recolorborders)
4285
4286 # Create page border shadows.
4287 if self._withTabs:
4288 self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0,
4289 fill = self._lightBorderColor, tags = 'lighttag')
4290 self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0,
4291 fill = self._darkBorderColor, tags = 'darktag')
4292 self._pageTop1Border = self.create_polygon(0, 0, 0, 0, 0, 0,
4293 fill = self._darkBorderColor, tags = 'lighttag')
4294 self._pageTop2Border = self.create_polygon(0, 0, 0, 0, 0, 0,
4295 fill = self._darkBorderColor, tags = 'lighttag')
4296 else:
4297 self._pageLeftBorder = self.create_polygon(0, 0, 0, 0, 0, 0,
4298 fill = self._darkBorderColor, tags = 'darktag')
4299 self._pageBottomRightBorder = self.create_polygon(0, 0, 0, 0, 0, 0,
4300 fill = self._lightBorderColor, tags = 'lighttag')
4301 self._pageTopBorder = self.create_polygon(0, 0, 0, 0, 0, 0,
4302 fill = self._darkBorderColor, tags = 'darktag')
4303
4304 # Check keywords and initialise options.
4305 self.initialiseoptions()
4306
4307 def insert(self, pageName, before = 0, **kw):
4308 if pageName in self._pageAttrs:
4309 msg = 'Page "%s" already exists.' % pageName
4310 raise ValueError(msg)
4311
4312 # Do this early to catch bad <before> spec before creating any items.
4313 beforeIndex = self.index(before, 1)
4314
4315 pageOptions = {}
4316 if self._withTabs:
4317 # Default tab button options.
4318 tabOptions = {
4319 'text' : pageName,
4320 'borderwidth' : 0,
4321 }
4322
4323 # Divide the keyword options into the 'page_' and 'tab_' options.
4324 for key in list(kw):
4325 if key[:5] == 'page_':
4326 pageOptions[key[5:]] = kw[key]
4327 del kw[key]
4328 elif self._withTabs and key[:4] == 'tab_':
4329 tabOptions[key[4:]] = kw[key]
4330 del kw[key]
4331 else:
4332 raise KeyError('Unknown option "' + key + '"')
4333
4334 # Create the frame to contain the page.
4335 page = self.createcomponent(pageName,
4336 (), 'Page',
4337 Tkinter.Frame, self._hull, **pageOptions)
4338
4339 attributes = {}
4340 attributes['page'] = page
4341 attributes['created'] = 0
4342
4343 if self._withTabs:
4344 # Create the button for the tab.
4345 def raiseThisPage(self = self, pageName = pageName):
4346 self.selectpage(pageName)
4347 tabOptions['command'] = raiseThisPage
4348 tab = self.createcomponent(pageName + '-tab',
4349 (), 'Tab',
4350 Tkinter.Button, self._hull, **tabOptions)
4351
4352 if self['arrownavigation']:
4353 # Allow the use of the arrow keys for Tab navigation:
4354 def next(event, self = self, pageName = pageName):
4355 self.nextpage(pageName)
4356 def prev(event, self = self, pageName = pageName):
4357 self.previouspage(pageName)
4358 tab.bind('<Left>', prev)
4359 tab.bind('<Right>', next)
4360
4361 attributes['tabbutton'] = tab
4362 attributes['tabreqwidth'] = tab.winfo_reqwidth()
4363 attributes['tabreqheight'] = tab.winfo_reqheight()
4364
4365 # Create the canvas item to manage the tab's button and the items
4366 # for the tab's shadow.
4367 windowitem = self.create_window(0, 0, window = tab, anchor = 'nw')
4368 lightshadow = self.create_polygon(0, 0, 0, 0, 0, 0,
4369 tags = 'lighttag', fill = self._lightBorderColor)
4370 darkshadow = self.create_polygon(0, 0, 0, 0, 0, 0,
4371 tags = 'darktag', fill = self._darkBorderColor)
4372 attributes['tabitems'] = (windowitem, lightshadow, darkshadow)
4373 self._pending['tabs'] = 1
4374
4375 self._pageAttrs[pageName] = attributes
4376 self._pageNames.insert(beforeIndex, pageName)
4377
4378 # If this is the first page added, make it the new top page
4379 # and call the create and raise callbacks.
4380 if self.getcurselection() is None:
4381 self._pending['topPage'] = pageName
4382 self._raiseNewTop(pageName)
4383
4384 self._layout()
4385 return page
4386
4387 def add(self, pageName, **kw):
4388 return self.insert(pageName, len(self._pageNames), **kw)
4389
4390 def delete(self, *pageNames):
4391 newTopPage = 0
4392 for page in pageNames:
4393 pageIndex = self.index(page)
4394 pageName = self._pageNames[pageIndex]
4395 pageInfo = self._pageAttrs[pageName]
4396
4397 if self.getcurselection() == pageName:
4398 if len(self._pageNames) == 1:
4399 newTopPage = 0
4400 self._pending['topPage'] = None
4401 elif pageIndex == len(self._pageNames) - 1:
4402 newTopPage = 1
4403 self._pending['topPage'] = self._pageNames[pageIndex - 1]
4404 else:
4405 newTopPage = 1
4406 self._pending['topPage'] = self._pageNames[pageIndex + 1]
4407
4408 if self._topPageName == pageName:
4409 self._hull.delete(self._topPageItem)
4410 self._topPageName = None
4411
4412 if self._withTabs:
4413 self.destroycomponent(pageName + '-tab')
4414 self._hull.delete(*pageInfo['tabitems'])
4415 self.destroycomponent(pageName)
4416 del self._pageAttrs[pageName]
4417 del self._pageNames[pageIndex]
4418
4419 # If the old top page was deleted and there are still pages
4420 # left in the notebook, call the create and raise callbacks.
4421 if newTopPage:
4422 pageName = self._pending['topPage']
4423 self._raiseNewTop(pageName)
4424
4425 if self._withTabs:
4426 self._pending['tabs'] = 1
4427 self._layout()
4428
4429 def page(self, pageIndex):
4430 pageName = self._pageNames[self.index(pageIndex)]
4431 return self._pageAttrs[pageName]['page']
4432
4433 def pagenames(self):
4434 return list(self._pageNames)
4435
4436 def getcurselection(self):
4437 if 'topPage' in self._pending:
4438 return self._pending['topPage']
4439 else:
4440 return self._topPageName
4441
4442 def tab(self, pageIndex):
4443 if self._withTabs:
4444 pageName = self._pageNames[self.index(pageIndex)]
4445 return self._pageAttrs[pageName]['tabbutton']
4446 else:
4447 return None
4448
4449 def index(self, index, forInsert = 0):
4450 listLength = len(self._pageNames)
4451 if isinstance(index, int):
4452 if forInsert and index <= listLength:
4453 return index
4454 elif not forInsert and index < listLength:
4455 return index
4456 else:
4457 raise ValueError('index "%s" is out of range' % index)
4458 elif index is END:
4459 if forInsert:
4460 return listLength
4461 elif listLength > 0:
4462 return listLength - 1
4463 else:
4464 raise ValueError('NoteBook has no pages')
4465 elif index is SELECT:
4466 if listLength == 0:
4467 raise ValueError('NoteBook has no pages')
4468 return self._pageNames.index(self.getcurselection())
4469 else:
4470 if index in self._pageNames:
4471 return self._pageNames.index(index)
4472 validValues = 'a name, a number, END or SELECT'
4473 raise ValueError('bad index "%s": must be %s' % (index, validValues))
4474
4475 def selectpage(self, page):
4476 pageName = self._pageNames[self.index(page)]
4477 oldTopPage = self.getcurselection()
4478 if pageName != oldTopPage:
4479 self._pending['topPage'] = pageName
4480 if oldTopPage == self._topPageName:
4481 self._hull.delete(self._topPageItem)
4482 cmd = self['lowercommand']
4483 if cmd is not None:
4484 cmd(oldTopPage)
4485 self._raiseNewTop(pageName)
4486
4487 self._layout()
4488
4489 # Set focus to the tab of new top page:
4490 if self._withTabs and self['arrownavigation']:
4491 self._pageAttrs[pageName]['tabbutton'].focus_set()
4492
4493 def previouspage(self, pageIndex = None):
4494 if pageIndex is None:
4495 curpage = self.index(SELECT)
4496 else:
4497 curpage = self.index(pageIndex)
4498 if curpage > 0:
4499 self.selectpage(curpage - 1)
4500
4501 def nextpage(self, pageIndex = None):
4502 if pageIndex is None:
4503 curpage = self.index(SELECT)
4504 else:
4505 curpage = self.index(pageIndex)
4506 if curpage < len(self._pageNames) - 1:
4507 self.selectpage(curpage + 1)
4508
4509 def setnaturalsize(self, pageNames = None):
4510 self.update_idletasks()
4511 maxPageWidth = 1
4512 maxPageHeight = 1
4513 if pageNames is None:
4514 pageNames = self.pagenames()
4515 for pageName in pageNames:
4516 pageInfo = self._pageAttrs[pageName]
4517 page = pageInfo['page']
4518 w = page.winfo_reqwidth()
4519 h = page.winfo_reqheight()
4520 if maxPageWidth < w:
4521 maxPageWidth = w
4522 if maxPageHeight < h:
4523 maxPageHeight = h
4524 pageBorder = self._borderWidth + self._pageMargin
4525 width = maxPageWidth + pageBorder * 2
4526 height = maxPageHeight + pageBorder * 2
4527
4528 if self._withTabs:
4529 maxTabHeight = 0
4530 for pageInfo in self._pageAttrs.values():
4531 if maxTabHeight < pageInfo['tabreqheight']:
4532 maxTabHeight = pageInfo['tabreqheight']
4533 height = height + maxTabHeight + self._borderWidth * 1.5
4534
4535 # Note that, since the hull is a canvas, the width and height
4536 # options specify the geometry *inside* the borderwidth and
4537 # highlightthickness.
4538 self.configure(hull_width = width, hull_height = height)
4539
4540 def recolorborders(self):
4541 self._pending['borderColor'] = 1
4542 self._layout()
4543
4544 def _handleMap(self, event):
4545 self._layout()
4546
4547 def _handleConfigure(self, event):
4548 self._canvasSize = (event.width, event.height)
4549 self._pending['size'] = 1
4550 self._layout()
4551
4552 def _raiseNewTop(self, pageName):
4553 if not self._pageAttrs[pageName]['created']:
4554 self._pageAttrs[pageName]['created'] = 1
4555 cmd = self['createcommand']
4556 if cmd is not None:
4557 cmd(pageName)
4558 cmd = self['raisecommand']
4559 if cmd is not None:
4560 cmd(pageName)
4561
4562 # This is the vertical layout of the notebook, from top (assuming
4563 # tabpos is 'n'):
4564 # hull highlightthickness (top)
4565 # hull borderwidth (top)
4566 # borderwidth (top border of tabs)
4567 # borderwidth * 0.5 (space for bevel)
4568 # tab button (maximum of requested height of all tab buttons)
4569 # borderwidth (border between tabs and page)
4570 # pagemargin (top)
4571 # the page itself
4572 # pagemargin (bottom)
4573 # borderwidth (border below page)
4574 # hull borderwidth (bottom)
4575 # hull highlightthickness (bottom)
4576 #
4577 # canvasBorder is sum of top two elements.
4578 # tabBottom is sum of top five elements.
4579 #
4580 # Horizontal layout (and also vertical layout when tabpos is None):
4581 # hull highlightthickness
4582 # hull borderwidth
4583 # borderwidth
4584 # pagemargin
4585 # the page itself
4586 # pagemargin
4587 # borderwidth
4588 # hull borderwidth
4589 # hull highlightthickness
4590 #
4591 def _layout(self):
4592 if not self.winfo_ismapped() or self._canvasSize is None:
4593 # Don't layout if the window is not displayed, or we
4594 # haven't yet received a <Configure> event.
4595 return
4596
4597 hullWidth, hullHeight = self._canvasSize
4598 borderWidth = self._borderWidth
4599 canvasBorder = int(self._hull['borderwidth']) + \
4600 int(self._hull['highlightthickness'])
4601 if not self._withTabs:
4602 self.tabBottom = canvasBorder
4603 oldTabBottom = self.tabBottom
4604
4605 if 'borderColor' in self._pending:
4606 self._lightBorderColor, self._darkBorderColor = \
4607 Color.bordercolors(self, self['hull_background'])
4608
4609 # Draw all the tabs.
4610 if self._withTabs and ('tabs' in self._pending or
4611 'size' in self._pending):
4612 # Find total requested width and maximum requested height
4613 # of tabs.
4614 sumTabReqWidth = 0
4615 maxTabHeight = 0
4616 for pageInfo in self._pageAttrs.values():
4617 sumTabReqWidth = sumTabReqWidth + pageInfo['tabreqwidth']
4618 if maxTabHeight < pageInfo['tabreqheight']:
4619 maxTabHeight = pageInfo['tabreqheight']
4620 if maxTabHeight != 0:
4621 # Add the top tab border plus a bit for the angled corners
4622 self.tabBottom = canvasBorder + maxTabHeight + borderWidth * 1.5
4623
4624 # Prepare for drawing the border around each tab button.
4625 tabTop = canvasBorder
4626 tabTop2 = tabTop + borderWidth
4627 tabTop3 = tabTop + borderWidth * 1.5
4628 tabBottom2 = self.tabBottom
4629 tabBottom = self.tabBottom + borderWidth
4630
4631 numTabs = len(self._pageNames)
4632 availableWidth = hullWidth - 2 * canvasBorder - \
4633 numTabs * 2 * borderWidth
4634 x = canvasBorder
4635 cumTabReqWidth = 0
4636 cumTabWidth = 0
4637
4638 # Position all the tabs.
4639 for pageName in self._pageNames:
4640 pageInfo = self._pageAttrs[pageName]
4641 (windowitem, lightshadow, darkshadow) = pageInfo['tabitems']
4642 if sumTabReqWidth <= availableWidth:
4643 tabwidth = pageInfo['tabreqwidth']
4644 else:
4645 # This ugly calculation ensures that, when the
4646 # notebook is not wide enough for the requested
4647 # widths of the tabs, the total width given to
4648 # the tabs exactly equals the available width,
4649 # without rounding errors.
4650 cumTabReqWidth = cumTabReqWidth + pageInfo['tabreqwidth']
4651 tmp = (2*cumTabReqWidth*availableWidth + sumTabReqWidth) \
4652 / (2 * sumTabReqWidth)
4653 tabwidth = tmp - cumTabWidth
4654 cumTabWidth = tmp
4655
4656 # Position the tab's button canvas item.
4657 self.coords(windowitem, x + borderWidth, tabTop3)
4658 self.itemconfigure(windowitem,
4659 width = tabwidth, height = maxTabHeight)
4660
4661 # Make a beautiful border around the tab.
4662 left = x
4663 left2 = left + borderWidth
4664 left3 = left + borderWidth * 1.5
4665 right = left + tabwidth + 2 * borderWidth
4666 right2 = left + tabwidth + borderWidth
4667 right3 = left + tabwidth + borderWidth * 0.5
4668
4669 self.coords(lightshadow,
4670 left, tabBottom2, left, tabTop2, left2, tabTop,
4671 right2, tabTop, right3, tabTop2, left3, tabTop2,
4672 left2, tabTop3, left2, tabBottom,
4673 )
4674 self.coords(darkshadow,
4675 right2, tabTop, right, tabTop2, right, tabBottom2,
4676 right2, tabBottom, right2, tabTop3, right3, tabTop2,
4677 )
4678 pageInfo['left'] = left
4679 pageInfo['right'] = right
4680
4681 x = x + tabwidth + 2 * borderWidth
4682
4683 # Redraw shadow under tabs so that it appears that tab for old
4684 # top page is lowered and that tab for new top page is raised.
4685 if self._withTabs and ('topPage' in self._pending or
4686 'tabs' in self._pending or 'size' in self._pending):
4687
4688 if self.getcurselection() is None:
4689 # No pages, so draw line across top of page area.
4690 self.coords(self._pageTop1Border,
4691 canvasBorder, self.tabBottom,
4692 hullWidth - canvasBorder, self.tabBottom,
4693 hullWidth - canvasBorder - borderWidth,
4694 self.tabBottom + borderWidth,
4695 borderWidth + canvasBorder, self.tabBottom + borderWidth,
4696 )
4697
4698 # Ignore second top border.
4699 self.coords(self._pageTop2Border, 0, 0, 0, 0, 0, 0)
4700 else:
4701 # Draw two lines, one on each side of the tab for the
4702 # top page, so that the tab appears to be raised.
4703 pageInfo = self._pageAttrs[self.getcurselection()]
4704 left = pageInfo['left']
4705 right = pageInfo['right']
4706 self.coords(self._pageTop1Border,
4707 canvasBorder, self.tabBottom,
4708 left, self.tabBottom,
4709 left + borderWidth, self.tabBottom + borderWidth,
4710 canvasBorder + borderWidth, self.tabBottom + borderWidth,
4711 )
4712
4713 self.coords(self._pageTop2Border,
4714 right, self.tabBottom,
4715 hullWidth - canvasBorder, self.tabBottom,
4716 hullWidth - canvasBorder - borderWidth,
4717 self.tabBottom + borderWidth,
4718 right - borderWidth, self.tabBottom + borderWidth,
4719 )
4720
4721 # Prevent bottom of dark border of tabs appearing over
4722 # page top border.
4723 self.tag_raise(self._pageTop1Border)
4724 self.tag_raise(self._pageTop2Border)
4725
4726 # Position the page border shadows.
4727 if 'size' in self._pending or oldTabBottom != self.tabBottom:
4728
4729 self.coords(self._pageLeftBorder,
4730 canvasBorder, self.tabBottom,
4731 borderWidth + canvasBorder,
4732 self.tabBottom + borderWidth,
4733 borderWidth + canvasBorder,
4734 hullHeight - canvasBorder - borderWidth,
4735 canvasBorder, hullHeight - canvasBorder,
4736 )
4737
4738 self.coords(self._pageBottomRightBorder,
4739 hullWidth - canvasBorder, self.tabBottom,
4740 hullWidth - canvasBorder, hullHeight - canvasBorder,
4741 canvasBorder, hullHeight - canvasBorder,
4742 borderWidth + canvasBorder,
4743 hullHeight - canvasBorder - borderWidth,
4744 hullWidth - canvasBorder - borderWidth,
4745 hullHeight - canvasBorder - borderWidth,
4746 hullWidth - canvasBorder - borderWidth,
4747 self.tabBottom + borderWidth,
4748 )
4749
4750 if not self._withTabs:
4751 self.coords(self._pageTopBorder,
4752 canvasBorder, self.tabBottom,
4753 hullWidth - canvasBorder, self.tabBottom,
4754 hullWidth - canvasBorder - borderWidth,
4755 self.tabBottom + borderWidth,
4756 borderWidth + canvasBorder, self.tabBottom + borderWidth,
4757 )
4758
4759 # Color borders.
4760 if 'borderColor' in self._pending:
4761 self.itemconfigure('lighttag', fill = self._lightBorderColor)
4762 self.itemconfigure('darktag', fill = self._darkBorderColor)
4763
4764 newTopPage = self._pending.get('topPage')
4765 pageBorder = borderWidth + self._pageMargin
4766
4767 # Raise new top page.
4768 if newTopPage is not None:
4769 self._topPageName = newTopPage
4770 self._topPageItem = self.create_window(
4771 pageBorder + canvasBorder, self.tabBottom + pageBorder,
4772 window = self._pageAttrs[newTopPage]['page'],
4773 anchor = 'nw',
4774 )
4775
4776 # Change position of top page if tab height has changed.
4777 if self._topPageName is not None and oldTabBottom != self.tabBottom:
4778 self.coords(self._topPageItem,
4779 pageBorder + canvasBorder, self.tabBottom + pageBorder)
4780
4781 # Change size of top page if,
4782 # 1) there is a new top page.
4783 # 2) canvas size has changed, but not if there is no top
4784 # page (eg: initially or when all pages deleted).
4785 # 3) tab height has changed, due to difference in the height of a tab
4786 if (newTopPage is not None or \
4787 'size' in self._pending and self._topPageName is not None
4788 or oldTabBottom != self.tabBottom):
4789 self.itemconfigure(self._topPageItem,
4790 width = hullWidth - 2 * canvasBorder - pageBorder * 2,
4791 height = hullHeight - 2 * canvasBorder - pageBorder * 2 -
4792 (self.tabBottom - canvasBorder),
4793 )
4794
4795 self._pending = {}
4796
4797 # Need to do forwarding to get the pack, grid, etc methods.
4798 # Unfortunately this means that all the other canvas methods are also
4799 # forwarded.
4800 forwardmethods(NoteBook, Tkinter.Canvas, '_hull')
4801
4802 ######################################################################
4803 ### File: PmwOptionMenu.py
4804
4805
4806 class OptionMenu(MegaWidget):
4807
4808 def __init__(self, parent = None, **kw):
4809
4810 # Define the megawidget options.
4811
4812 optiondefs = (
4813 ('command', None, None),
4814 ('items', (), INITOPT),
4815 ('initialitem', None, INITOPT),
4816 ('labelmargin', 0, INITOPT),
4817 ('labelpos', None, INITOPT),
4818 ('sticky', 'ew', INITOPT),
4819 )
4820 self.defineoptions(kw, optiondefs)
4821
4822 # Initialise the base class (after defining the options).
4823 MegaWidget.__init__(self, parent)
4824
4825 # Create the components.
4826 interior = self.interior()
4827
4828 self._menubutton = self.createcomponent('menubutton',
4829 (), None,
4830 Tkinter.Menubutton, (interior,),
4831 borderwidth = 2,
4832 indicatoron = 1,
4833 relief = 'raised',
4834 anchor = 'c',
4835 highlightthickness = 2,
4836 direction = 'flush',
4837 takefocus = 1,
4838 )
4839 self._menubutton.grid(column = 2, row = 2, sticky = self['sticky'])
4840
4841 self._menu = self.createcomponent('menu',
4842 (), None,
4843 Tkinter.Menu, (self._menubutton,),
4844 tearoff=0
4845 )
4846 self._menubutton.configure(menu = self._menu)
4847
4848 interior.grid_columnconfigure(2, weight = 1)
4849 interior.grid_rowconfigure(2, weight = 1)
4850
4851 # Create the label.
4852 self.createlabel(interior)
4853
4854 # Add the items specified by the initialisation option.
4855 self._itemList = []
4856 self.setitems(self['items'], self['initialitem'])
4857
4858 # Check keywords and initialise options.
4859 self.initialiseoptions()
4860
4861 def setitems(self, items, index = None):
4862
4863 # Clean up old items and callback commands.
4864 for oldIndex in range(len(self._itemList)):
4865 tclCommandName = str(self._menu.entrycget(oldIndex, 'command'))
4866 if tclCommandName != '':
4867 self._menu.deletecommand(tclCommandName)
4868 self._menu.delete(0, 'end')
4869 self._itemList = list(items)
4870
4871 # Set the items in the menu component.
4872 for item in items:
4873 self._menu.add_command(label = item,
4874 command = lambda self = self, item = item: self._invoke(item))
4875
4876 # Set the currently selected value.
4877 if index is None:
4878 var = str(self._menubutton.cget('textvariable'))
4879 if var != '':
4880 # None means do not change text variable.
4881 return
4882 if len(items) == 0:
4883 text = ''
4884 elif str(self._menubutton.cget('text')) in items:
4885 # Do not change selection if it is still valid
4886 return
4887 else:
4888 text = items[0]
4889 else:
4890 index = self.index(index)
4891 text = self._itemList[index]
4892
4893 self.setvalue(text)
4894
4895 def getcurselection(self):
4896 var = str(self._menubutton.cget('textvariable'))
4897 if var == '':
4898 return str(self._menubutton.cget('text'))
4899 else:
4900 return self._menu.tk.globalgetvar(var)
4901
4902 def getvalue(self):
4903 return self.getcurselection()
4904
4905 def setvalue(self, text):
4906 var = str(self._menubutton.cget('textvariable'))
4907 if var == '':
4908 self._menubutton.configure(text = text)
4909 else:
4910 self._menu.tk.globalsetvar(var, text)
4911
4912 def index(self, index):
4913 listLength = len(self._itemList)
4914 if isinstance(index, int):
4915 if index < listLength:
4916 return index
4917 else:
4918 raise ValueError('index "%s" is out of range' % index)
4919 elif index is END:
4920 if listLength > 0:
4921 return listLength - 1
4922 else:
4923 raise ValueError('OptionMenu has no items')
4924 else:
4925 if index is SELECT:
4926 if listLength > 0:
4927 index = self.getcurselection()
4928 else:
4929 raise ValueError('OptionMenu has no items')
4930 if index in self._itemList:
4931 return self._itemList.index(index)
4932 raise ValueError('bad index "%s": must be a ' \
4933 'name, a number, END or SELECT' % (index,))
4934
4935 def invoke(self, index = SELECT):
4936 index = self.index(index)
4937 text = self._itemList[index]
4938
4939 return self._invoke(text)
4940
4941 def _invoke(self, text):
4942 self.setvalue(text)
4943
4944 command = self['command']
4945 if hasattr(command, '__call__'):
4946 return command(text)
4947
4948 ######################################################################
4949 ### File: PmwPanedWidget.py
4950 # PanedWidget
4951 # a frame which may contain several resizable sub-frames
4952
4953 import sys
4954
4955
4956 class PanedWidget(MegaWidget):
4957
4958 def __init__(self, parent = None, **kw):
4959
4960 # Define the megawidget options.
4961
4962 optiondefs = (
4963 ('command', None, None),
4964 ('orient', 'vertical', INITOPT),
4965 ('separatorrelief', 'sunken', INITOPT),
4966 ('separatorthickness', 2, INITOPT),
4967 ('handlesize', 8, INITOPT),
4968 ('hull_width', 400, None),
4969 ('hull_height', 400, None),
4970 )
4971 self.defineoptions(kw, optiondefs,
4972 dynamicGroups = ('Frame', 'Separator', 'Handle'))
4973
4974 # Initialise the base class (after defining the options).
4975 MegaWidget.__init__(self, parent)
4976
4977 self.bind('<Configure>', self._handleConfigure)
4978
4979 if self['orient'] not in ('horizontal', 'vertical'):
4980 raise ValueError('bad orient option ' + repr(self['orient']) + \
4981 ': must be either \'horizontal\' or \'vertical\'')
4982
4983 self._separatorThickness = self['separatorthickness']
4984 self._handleSize = self['handlesize']
4985 self._paneNames = [] # List of pane names
4986 self._paneAttrs = {} # Map from pane name to pane info
4987
4988 self._timerId = None
4989 self._frame = {}
4990 self._separator = []
4991 self._button = []
4992 self._totalSize = 0
4993 self._movePending = 0
4994 self._relsize = {}
4995 self._relmin = {}
4996 self._relmax = {}
4997 self._size = {}
4998 self._min = {}
4999 self._max = {}
5000 self._rootp = None
5001 self._curSize = None
5002 self._beforeLimit = None
5003 self._afterLimit = None
5004 self._buttonIsDown = 0
5005 self._majorSize = 100
5006 self._minorSize = 100
5007
5008 # Check keywords and initialise options.
5009 self.initialiseoptions()
5010
5011 def insert(self, name, before = 0, **kw):
5012 # Parse <kw> for options.
5013 self._initPaneOptions(name)
5014 self._parsePaneOptions(name, kw)
5015
5016 insertPos = self._nameToIndex(before)
5017 atEnd = (insertPos == len(self._paneNames))
5018
5019 # Add the frame.
5020 self._paneNames[insertPos:insertPos] = [name]
5021 self._frame[name] = self.createcomponent(name,
5022 (), 'Frame',
5023 Tkinter.Frame, (self.interior(),))
5024
5025 # Add separator, if necessary.
5026 if len(self._paneNames) > 1:
5027 self._addSeparator()
5028 else:
5029 self._separator.append(None)
5030 self._button.append(None)
5031
5032 # Add the new frame and adjust the PanedWidget
5033 if atEnd:
5034 size = self._size[name]
5035 if size > 0 or self._relsize[name] is not None:
5036 if self['orient'] == 'vertical':
5037 self._frame[name].place(x=0, relwidth=1,
5038 height=size, y=self._totalSize)
5039 else:
5040 self._frame[name].place(y=0, relheight=1,
5041 width=size, x=self._totalSize)
5042 else:
5043 if self['orient'] == 'vertical':
5044 self._frame[name].place(x=0, relwidth=1,
5045 y=self._totalSize)
5046 else:
5047 self._frame[name].place(y=0, relheight=1,
5048 x=self._totalSize)
5049 else:
5050 self._updateSizes()
5051
5052 self._totalSize = self._totalSize + self._size[name]
5053 return self._frame[name]
5054
5055 def add(self, name, **kw):
5056 return self.insert(name, len(self._paneNames), **kw)
5057
5058 def delete(self, name):
5059 deletePos = self._nameToIndex(name)
5060 name = self._paneNames[deletePos]
5061 self.destroycomponent(name)
5062 del self._paneNames[deletePos]
5063 del self._frame[name]
5064 del self._size[name]
5065 del self._min[name]
5066 del self._max[name]
5067 del self._relsize[name]
5068 del self._relmin[name]
5069 del self._relmax[name]
5070
5071 last = len(self._paneNames)
5072 del self._separator[last]
5073 del self._button[last]
5074 if last > 0:
5075 self.destroycomponent(self._sepName(last))
5076 self.destroycomponent(self._buttonName(last))
5077
5078 self._plotHandles()
5079
5080 def setnaturalsize(self):
5081 self.update_idletasks()
5082 totalWidth = 0
5083 totalHeight = 0
5084 maxWidth = 0
5085 maxHeight = 0
5086 for name in self._paneNames:
5087 frame = self._frame[name]
5088 w = frame.winfo_reqwidth()
5089 h = frame.winfo_reqheight()
5090 totalWidth = totalWidth + w
5091 totalHeight = totalHeight + h
5092 if maxWidth < w:
5093 maxWidth = w
5094 if maxHeight < h:
5095 maxHeight = h
5096
5097 # Note that, since the hull is a frame, the width and height
5098 # options specify the geometry *outside* the borderwidth and
5099 # highlightthickness.
5100 bw = int(str(self.cget('hull_borderwidth')))
5101 hl = int(str(self.cget('hull_highlightthickness')))
5102 extra = (bw + hl) * 2
5103 if str(self.cget('orient')) == 'horizontal':
5104 totalWidth = totalWidth + extra
5105 maxHeight = maxHeight + extra
5106 self.configure(hull_width = totalWidth, hull_height = maxHeight)
5107 else:
5108 totalHeight = (totalHeight + extra +
5109 (len(self._paneNames) - 1) * self._separatorThickness)
5110 maxWidth = maxWidth + extra
5111 self.configure(hull_width = maxWidth, hull_height = totalHeight)
5112
5113 def move(self, name, newPos, newPosOffset = 0):
5114
5115 # see if we can spare ourselves some work
5116 numPanes = len(self._paneNames)
5117 if numPanes < 2:
5118 return
5119
5120 newPos = self._nameToIndex(newPos) + newPosOffset
5121 if newPos < 0 or newPos >=numPanes:
5122 return
5123
5124 deletePos = self._nameToIndex(name)
5125
5126 if deletePos == newPos:
5127 # inserting over ourself is a no-op
5128 return
5129
5130 # delete name from old position in list
5131 name = self._paneNames[deletePos]
5132 del self._paneNames[deletePos]
5133
5134 # place in new position
5135 self._paneNames[newPos:newPos] = [name]
5136
5137 # force everything to redraw
5138 self._plotHandles()
5139 self._updateSizes()
5140
5141 def _nameToIndex(self, nameOrIndex):
5142 try:
5143 pos = self._paneNames.index(nameOrIndex)
5144 except ValueError:
5145 pos = nameOrIndex
5146
5147 return pos
5148
5149 def _initPaneOptions(self, name):
5150 # Set defaults.
5151 self._size[name] = 0
5152 self._relsize[name] = None
5153 self._min[name] = 0
5154 self._relmin[name] = None
5155 self._max[name] = 100000
5156 self._relmax[name] = None
5157
5158 def _parsePaneOptions(self, name, args):
5159 # Parse <args> for options.
5160 for arg, value in args.items():
5161 if isinstance(value, float):
5162 relvalue = value
5163 value = self._absSize(relvalue)
5164 else:
5165 relvalue = None
5166
5167 if arg == 'size':
5168 self._size[name], self._relsize[name] = value, relvalue
5169 elif arg == 'min':
5170 self._min[name], self._relmin[name] = value, relvalue
5171 elif arg == 'max':
5172 self._max[name], self._relmax[name] = value, relvalue
5173 else:
5174 raise ValueError('keyword must be "size", "min", or "max"')
5175
5176 def _absSize(self, relvalue):
5177 return int(round(relvalue * self._majorSize))
5178
5179 def _sepName(self, n):
5180 return 'separator-%d' % n
5181
5182 def _buttonName(self, n):
5183 return 'handle-%d' % n
5184
5185 def _addSeparator(self):
5186 n = len(self._paneNames) - 1
5187
5188 downFunc = lambda event, s = self, num=n: s._btnDown(event, num)
5189 upFunc = lambda event, s = self, num=n: s._btnUp(event, num)
5190 moveFunc = lambda event, s = self, num=n: s._btnMove(event, num)
5191
5192 # Create the line dividing the panes.
5193 sep = self.createcomponent(self._sepName(n),
5194 (), 'Separator',
5195 Tkinter.Frame, (self.interior(),),
5196 borderwidth = 1,
5197 relief = self['separatorrelief'])
5198 self._separator.append(sep)
5199
5200 sep.bind('<ButtonPress-1>', downFunc)
5201 sep.bind('<Any-ButtonRelease-1>', upFunc)
5202 sep.bind('<B1-Motion>', moveFunc)
5203
5204 if self['orient'] == 'vertical':
5205 cursor = 'sb_v_double_arrow'
5206 sep.configure(height = self._separatorThickness,
5207 width = 10000, cursor = cursor)
5208 else:
5209 cursor = 'sb_h_double_arrow'
5210 sep.configure(width = self._separatorThickness,
5211 height = 10000, cursor = cursor)
5212
5213 self._totalSize = self._totalSize + self._separatorThickness
5214
5215 # Create the handle on the dividing line.
5216 handle = self.createcomponent(self._buttonName(n),
5217 (), 'Handle',
5218 Tkinter.Frame, (self.interior(),),
5219 relief = 'raised',
5220 borderwidth = 1,
5221 width = self._handleSize,
5222 height = self._handleSize,
5223 cursor = cursor,
5224 )
5225 self._button.append(handle)
5226
5227 handle.bind('<ButtonPress-1>', downFunc)
5228 handle.bind('<Any-ButtonRelease-1>', upFunc)
5229 handle.bind('<B1-Motion>', moveFunc)
5230
5231 self._plotHandles()
5232
5233 for i in range(1, len(self._paneNames)):
5234 self._separator[i].tkraise()
5235 for i in range(1, len(self._paneNames)):
5236 self._button[i].tkraise()
5237
5238 def _btnUp(self, event, item):
5239 self._buttonIsDown = 0
5240 self._updateSizes()
5241 try:
5242 self._button[item].configure(relief='raised')
5243 except:
5244 pass
5245
5246 def _btnDown(self, event, item):
5247 self._button[item].configure(relief='sunken')
5248 self._getMotionLimit(item)
5249 self._buttonIsDown = 1
5250 self._movePending = 0
5251
5252 def _handleConfigure(self, event = None):
5253 self._getNaturalSizes()
5254 if self._totalSize == 0:
5255 return
5256
5257 iterRange = list(self._paneNames)
5258 iterRange.reverse()
5259 if self._majorSize > self._totalSize:
5260 n = self._majorSize - self._totalSize
5261 self._iterate(iterRange, self._grow, n)
5262 elif self._majorSize < self._totalSize:
5263 n = self._totalSize - self._majorSize
5264 self._iterate(iterRange, self._shrink, n)
5265
5266 self._plotHandles()
5267 self._updateSizes()
5268
5269 def _getNaturalSizes(self):
5270 # Must call this in order to get correct winfo_width, winfo_height
5271 self.update_idletasks()
5272
5273 self._totalSize = 0
5274
5275 if self['orient'] == 'vertical':
5276 self._majorSize = self.winfo_height()
5277 self._minorSize = self.winfo_width()
5278 majorspec = Tkinter.Frame.winfo_reqheight
5279 else:
5280 self._majorSize = self.winfo_width()
5281 self._minorSize = self.winfo_height()
5282 majorspec = Tkinter.Frame.winfo_reqwidth
5283
5284 bw = int(str(self.cget('hull_borderwidth')))
5285 hl = int(str(self.cget('hull_highlightthickness')))
5286 extra = (bw + hl) * 2
5287 self._majorSize = self._majorSize - extra
5288 self._minorSize = self._minorSize - extra
5289
5290 if self._majorSize < 0:
5291 self._majorSize = 0
5292 if self._minorSize < 0:
5293 self._minorSize = 0
5294
5295 for name in self._paneNames:
5296 # adjust the absolute sizes first...
5297 if self._relsize[name] is None:
5298 #special case
5299 if self._size[name] == 0:
5300 self._size[name] = majorspec(self._frame[name])
5301 self._setrel(name)
5302 else:
5303 self._size[name] = self._absSize(self._relsize[name])
5304
5305 if self._relmin[name] is not None:
5306 self._min[name] = self._absSize(self._relmin[name])
5307 if self._relmax[name] is not None:
5308 self._max[name] = self._absSize(self._relmax[name])
5309
5310 # now adjust sizes
5311 if self._size[name] < self._min[name]:
5312 self._size[name] = self._min[name]
5313 self._setrel(name)
5314
5315 if self._size[name] > self._max[name]:
5316 self._size[name] = self._max[name]
5317 self._setrel(name)
5318
5319 self._totalSize = self._totalSize + self._size[name]
5320
5321 # adjust for separators
5322 self._totalSize = (self._totalSize +
5323 (len(self._paneNames) - 1) * self._separatorThickness)
5324
5325 def _setrel(self, name):
5326 if self._relsize[name] is not None:
5327 if self._majorSize != 0:
5328 self._relsize[name] = round(self._size[name]) / self._majorSize
5329
5330 def _iterate(self, names, proc, n):
5331 for i in names:
5332 n = proc(i, n)
5333 if n == 0:
5334 break
5335
5336 def _grow(self, name, n):
5337 canGrow = self._max[name] - self._size[name]
5338
5339 if canGrow > n:
5340 self._size[name] = self._size[name] + n
5341 self._setrel(name)
5342 return 0
5343 elif canGrow > 0:
5344 self._size[name] = self._max[name]
5345 self._setrel(name)
5346 n = n - canGrow
5347
5348 return n
5349
5350 def _shrink(self, name, n):
5351 canShrink = self._size[name] - self._min[name]
5352
5353 if canShrink > n:
5354 self._size[name] = self._size[name] - n
5355 self._setrel(name)
5356 return 0
5357 elif canShrink > 0:
5358 self._size[name] = self._min[name]
5359 self._setrel(name)
5360 n = n - canShrink
5361
5362 return n
5363
5364 def _updateSizes(self):
5365 totalSize = 0
5366
5367 for name in self._paneNames:
5368 size = self._size[name]
5369 if self['orient'] == 'vertical':
5370 self._frame[name].place(x = 0, relwidth = 1,
5371 y = totalSize,
5372 height = size)
5373 else:
5374 self._frame[name].place(y = 0, relheight = 1,
5375 x = totalSize,
5376 width = size)
5377
5378 totalSize = totalSize + size + self._separatorThickness
5379
5380 # Invoke the callback command
5381 cmd = self['command']
5382 if hasattr(cmd, '__call__'):
5383 cmd([self._size[x] for x in self._paneNames])
5384
5385 def _plotHandles(self):
5386 if len(self._paneNames) == 0:
5387 return
5388
5389 if self['orient'] == 'vertical':
5390 btnp = self._minorSize - 13
5391 else:
5392 h = self._minorSize
5393
5394 if h > 18:
5395 btnp = 9
5396 else:
5397 btnp = h - 9
5398
5399 firstPane = self._paneNames[0]
5400 totalSize = self._size[firstPane]
5401
5402 first = 1
5403 last = len(self._paneNames) - 1
5404
5405 # loop from first to last, inclusive
5406 for i in range(1, last + 1):
5407
5408 handlepos = totalSize - 3
5409 prevSize = self._size[self._paneNames[i - 1]]
5410 nextSize = self._size[self._paneNames[i]]
5411
5412 offset1 = 0
5413
5414 if i == first:
5415 if prevSize < 4:
5416 offset1 = 4 - prevSize
5417 else:
5418 if prevSize < 8:
5419 offset1 = (8 - prevSize) / 2
5420
5421 offset2 = 0
5422
5423 if i == last:
5424 if nextSize < 4:
5425 offset2 = nextSize - 4
5426 else:
5427 if nextSize < 8:
5428 offset2 = (nextSize - 8) / 2
5429
5430 handlepos = handlepos + offset1
5431
5432 if self['orient'] == 'vertical':
5433 height = 8 - offset1 + offset2
5434
5435 if height > 1:
5436 self._button[i].configure(height = height)
5437 self._button[i].place(x = btnp, y = handlepos)
5438 else:
5439 self._button[i].place_forget()
5440
5441 self._separator[i].place(x = 0, y = totalSize,
5442 relwidth = 1)
5443 else:
5444 width = 8 - offset1 + offset2
5445
5446 if width > 1:
5447 self._button[i].configure(width = width)
5448 self._button[i].place(y = btnp, x = handlepos)
5449 else:
5450 self._button[i].place_forget()
5451
5452 self._separator[i].place(y = 0, x = totalSize,
5453 relheight = 1)
5454
5455 totalSize = totalSize + nextSize + self._separatorThickness
5456
5457 def pane(self, name):
5458 return self._frame[self._paneNames[self._nameToIndex(name)]]
5459
5460 # Return the name of all panes
5461 def panes(self):
5462 return list(self._paneNames)
5463
5464 def configurepane(self, name, **kw):
5465 name = self._paneNames[self._nameToIndex(name)]
5466 self._parsePaneOptions(name, kw)
5467 self._handleConfigure()
5468
5469 def updatelayout(self):
5470 self._handleConfigure()
5471
5472 def _getMotionLimit(self, item):
5473 curBefore = (item - 1) * self._separatorThickness
5474 minBefore, maxBefore = curBefore, curBefore
5475
5476 for name in self._paneNames[:item]:
5477 curBefore = curBefore + self._size[name]
5478 minBefore = minBefore + self._min[name]
5479 maxBefore = maxBefore + self._max[name]
5480
5481 curAfter = (len(self._paneNames) - item) * self._separatorThickness
5482 minAfter, maxAfter = curAfter, curAfter
5483 for name in self._paneNames[item:]:
5484 curAfter = curAfter + self._size[name]
5485 minAfter = minAfter + self._min[name]
5486 maxAfter = maxAfter + self._max[name]
5487
5488 beforeToGo = min(curBefore - minBefore, maxAfter - curAfter)
5489 afterToGo = min(curAfter - minAfter, maxBefore - curBefore)
5490
5491 self._beforeLimit = curBefore - beforeToGo
5492 self._afterLimit = curBefore + afterToGo
5493 self._curSize = curBefore
5494
5495 self._plotHandles()
5496
5497 # Compress the motion so that update is quick even on slow machines
5498 #
5499 # theRootp = root position (either rootx or rooty)
5500 def _btnMove(self, event, item):
5501 self._rootp = event
5502
5503 if self._movePending == 0:
5504 self._timerId = self.after_idle(
5505 lambda s = self, i = item: s._btnMoveCompressed(i))
5506 self._movePending = 1
5507
5508 def destroy(self):
5509 if self._timerId is not None:
5510 self.after_cancel(self._timerId)
5511 self._timerId = None
5512 MegaWidget.destroy(self)
5513
5514 def _btnMoveCompressed(self, item):
5515 if not self._buttonIsDown:
5516 return
5517
5518 if self['orient'] == 'vertical':
5519 p = self._rootp.y_root - self.winfo_rooty()
5520 else:
5521 p = self._rootp.x_root - self.winfo_rootx()
5522
5523 if p == self._curSize:
5524 self._movePending = 0
5525 return
5526
5527 if p < self._beforeLimit:
5528 p = self._beforeLimit
5529
5530 if p >= self._afterLimit:
5531 p = self._afterLimit
5532
5533 self._calculateChange(item, p)
5534 self.update_idletasks()
5535 self._movePending = 0
5536
5537 # Calculate the change in response to mouse motions
5538 def _calculateChange(self, item, p):
5539
5540 if p < self._curSize:
5541 self._moveBefore(item, p)
5542 elif p > self._curSize:
5543 self._moveAfter(item, p)
5544
5545 self._plotHandles()
5546
5547 def _moveBefore(self, item, p):
5548 n = self._curSize - p
5549
5550 # Shrink the frames before
5551 iterRange = list(self._paneNames[:item])
5552 iterRange.reverse()
5553 self._iterate(iterRange, self._shrink, n)
5554
5555 # Adjust the frames after
5556 iterRange = self._paneNames[item:]
5557 self._iterate(iterRange, self._grow, n)
5558
5559 self._curSize = p
5560
5561 def _moveAfter(self, item, p):
5562 n = p - self._curSize
5563
5564 # Shrink the frames after
5565 iterRange = self._paneNames[item:]
5566 self._iterate(iterRange, self._shrink, n)
5567
5568 # Adjust the frames before
5569 iterRange = list(self._paneNames[:item])
5570 iterRange.reverse()
5571 self._iterate(iterRange, self._grow, n)
5572
5573 self._curSize = p
5574
5575 ######################################################################
5576 ### File: PmwPromptDialog.py
5577 # Based on iwidgets2.2.0/promptdialog.itk code.
5578
5579
5580
5581 # A Dialog with an entryfield
5582
5583 class PromptDialog(Dialog):
5584 def __init__(self, parent = None, **kw):
5585 # Define the megawidget options.
5586
5587 optiondefs = (
5588 ('borderx', 20, INITOPT),
5589 ('bordery', 20, INITOPT),
5590 )
5591 self.defineoptions(kw, optiondefs)
5592
5593 # Initialise the base class (after defining the options).
5594 Dialog.__init__(self, parent)
5595
5596 # Create the components.
5597 interior = self.interior()
5598 aliases = (
5599 ('entry', 'entryfield_entry'),
5600 ('label', 'entryfield_label'),
5601 )
5602 self._promptDialogEntry = self.createcomponent('entryfield',
5603 aliases, None,
5604 EntryField, (interior,))
5605 self._promptDialogEntry.pack(fill='x', expand=1,
5606 padx = self['borderx'], pady = self['bordery'])
5607
5608 if 'activatecommand' not in kw:
5609 # Whenever this dialog is activated, set the focus to the
5610 # EntryField's entry widget.
5611 tkentry = self.component('entry')
5612 self.configure(activatecommand = tkentry.focus_set)
5613
5614 # Check keywords and initialise options.
5615 self.initialiseoptions()
5616
5617 # Supply aliases to some of the entry component methods.
5618 def insertentry(self, index, text):
5619 self._promptDialogEntry.insert(index, text)
5620
5621 def deleteentry(self, first, last=None):
5622 self._promptDialogEntry.delete(first, last)
5623
5624 def indexentry(self, index):
5625 return self._promptDialogEntry.index(index)
5626
5627 forwardmethods(PromptDialog, EntryField, '_promptDialogEntry')
5628
5629 ######################################################################
5630 ### File: PmwRadioSelect.py
5631
5632
5633 class RadioSelect(MegaWidget):
5634 # A collection of several buttons. In single mode, only one
5635 # button may be selected. In multiple mode, any number of buttons
5636 # may be selected.
5637
5638 def __init__(self, parent = None, **kw):
5639
5640 # Define the megawidget options.
5641
5642 optiondefs = (
5643 ('buttontype', 'button', INITOPT),
5644 ('command', None, None),
5645 ('labelmargin', 0, INITOPT),
5646 ('labelpos', None, INITOPT),
5647 ('orient', 'horizontal', INITOPT),
5648 ('padx', 5, INITOPT),
5649 ('pady', 5, INITOPT),
5650 ('selectmode', 'single', INITOPT),
5651 )
5652 self.defineoptions(kw, optiondefs, dynamicGroups = ('Button',))
5653
5654 # Initialise the base class (after defining the options).
5655 MegaWidget.__init__(self, parent)
5656
5657 # Create the components.
5658 interior = self.interior()
5659 if self['labelpos'] is None:
5660 self._radioSelectFrame = self._hull
5661 else:
5662 self._radioSelectFrame = self.createcomponent('frame',
5663 (), None,
5664 Tkinter.Frame, (interior,))
5665 self._radioSelectFrame.grid(column=2, row=2, sticky='nsew')
5666 interior.grid_columnconfigure(2, weight=1)
5667 interior.grid_rowconfigure(2, weight=1)
5668
5669 self.createlabel(interior)
5670
5671 # Initialise instance variables.
5672 self._buttonList = []
5673 if self['selectmode'] == 'single':
5674 self._singleSelect = 1
5675 elif self['selectmode'] == 'multiple':
5676 self._singleSelect = 0
5677 else:
5678 raise ValueError('bad selectmode option "' + \
5679 self['selectmode'] + '": should be single or multiple')
5680
5681 if self['buttontype'] == 'button':
5682 self.buttonClass = Tkinter.Button
5683 elif self['buttontype'] == 'radiobutton':
5684 self._singleSelect = 1
5685 self.var = Tkinter.StringVar()
5686 self.buttonClass = Tkinter.Radiobutton
5687 elif self['buttontype'] == 'checkbutton':
5688 self._singleSelect = 0
5689 self.buttonClass = Tkinter.Checkbutton
5690 else:
5691 raise ValueError('bad buttontype option "' + \
5692 self['buttontype'] + \
5693 '": should be button, radiobutton or checkbutton')
5694
5695 if self._singleSelect:
5696 self.selection = None
5697 else:
5698 self.selection = []
5699
5700 if self['orient'] not in ('horizontal', 'vertical'):
5701 raise ValueError('bad orient option ' + repr(self['orient']) + \
5702 ': must be either \'horizontal\' or \'vertical\'')
5703
5704 # Check keywords and initialise options.
5705 self.initialiseoptions()
5706
5707 def getcurselection(self):
5708 if self._singleSelect:
5709 return self.selection
5710 else:
5711 return tuple(self.selection)
5712
5713 def getvalue(self):
5714 return self.getcurselection()
5715
5716 def setvalue(self, textOrList):
5717 if self._singleSelect:
5718 self.__setSingleValue(textOrList)
5719 else:
5720 # Multiple selections
5721 oldselection = self.selection
5722 self.selection = textOrList
5723 for button in self._buttonList:
5724 if button in oldselection:
5725 if button not in self.selection:
5726 # button is currently selected but should not be
5727 widget = self.component(button)
5728 if self['buttontype'] == 'checkbutton':
5729 widget.deselect()
5730 else: # Button
5731 widget.configure(relief='raised')
5732 else:
5733 if button in self.selection:
5734 # button is not currently selected but should be
5735 widget = self.component(button)
5736 if self['buttontype'] == 'checkbutton':
5737 widget.select()
5738 else: # Button
5739 widget.configure(relief='sunken')
5740
5741 def numbuttons(self):
5742 return len(self._buttonList)
5743
5744 def index(self, index):
5745 # Return the integer index of the button with the given index.
5746
5747 listLength = len(self._buttonList)
5748 if isinstance(index, int):
5749 if index < listLength:
5750 return index
5751 else:
5752 raise ValueError('index "%s" is out of range' % index)
5753 elif index is END:
5754 if listLength > 0:
5755 return listLength - 1
5756 else:
5757 raise ValueError('RadioSelect has no buttons')
5758 else:
5759 for count in range(listLength):
5760 name = self._buttonList[count]
5761 if index == name:
5762 return count
5763 validValues = 'a name, a number or END'
5764 raise ValueError('bad index "%s": must be %s' % (index, validValues))
5765
5766 def button(self, buttonIndex):
5767 name = self._buttonList[self.index(buttonIndex)]
5768 return self.component(name)
5769
5770 def add(self, componentName, **kw):
5771 if componentName in self._buttonList:
5772 raise ValueError('button "%s" already exists' % componentName)
5773
5774 kw['command'] = \
5775 lambda self=self, name=componentName: self.invoke(name)
5776 if 'text' not in kw:
5777 kw['text'] = componentName
5778
5779 if self['buttontype'] == 'radiobutton':
5780 if 'anchor' not in kw:
5781 kw['anchor'] = 'w'
5782 if 'variable' not in kw:
5783 kw['variable'] = self.var
5784 if 'value' not in kw:
5785 kw['value'] = kw['text']
5786 elif self['buttontype'] == 'checkbutton':
5787 if 'anchor' not in kw:
5788 kw['anchor'] = 'w'
5789
5790 button = self.createcomponent(componentName,
5791 (), 'Button',
5792 self.buttonClass, (self._radioSelectFrame,), **kw)
5793
5794 if self['orient'] == 'horizontal':
5795 self._radioSelectFrame.grid_rowconfigure(0, weight=1)
5796 col = len(self._buttonList)
5797 button.grid(column=col, row=0, padx = self['padx'],
5798 pady = self['pady'], sticky='nsew')
5799 self._radioSelectFrame.grid_columnconfigure(col, weight=1)
5800 else:
5801 self._radioSelectFrame.grid_columnconfigure(0, weight=1)
5802 row = len(self._buttonList)
5803 button.grid(column=0, row=row, padx = self['padx'],
5804 pady = self['pady'], sticky='ew')
5805 self._radioSelectFrame.grid_rowconfigure(row, weight=1)
5806
5807 self._buttonList.append(componentName)
5808 return button
5809
5810 def deleteall(self):
5811 for name in self._buttonList:
5812 self.destroycomponent(name)
5813 self._buttonList = []
5814 if self._singleSelect:
5815 self.selection = None
5816 else:
5817 self.selection = []
5818
5819 def __setSingleValue(self, value):
5820 self.selection = value
5821 if self['buttontype'] == 'radiobutton':
5822 widget = self.component(value)
5823 widget.select()
5824 else: # Button
5825 for button in self._buttonList:
5826 widget = self.component(button)
5827 if button == value:
5828 widget.configure(relief='sunken')
5829 else:
5830 widget.configure(relief='raised')
5831
5832 def invoke(self, index):
5833 index = self.index(index)
5834 name = self._buttonList[index]
5835
5836 if self._singleSelect:
5837 self.__setSingleValue(name)
5838 command = self['command']
5839 if hasattr(command, '__call__'):
5840 return command(name)
5841 else:
5842 # Multiple selections
5843 widget = self.component(name)
5844 if name in self.selection:
5845 if self['buttontype'] == 'checkbutton':
5846 widget.deselect()
5847 else:
5848 widget.configure(relief='raised')
5849 self.selection.remove(name)
5850 state = 0
5851 else:
5852 if self['buttontype'] == 'checkbutton':
5853 widget.select()
5854 else:
5855 widget.configure(relief='sunken')
5856 self.selection.append(name)
5857 state = 1
5858
5859 command = self['command']
5860 if hasattr(command, '__call__'):
5861 return command(name, state)
5862
5863 ######################################################################
5864 ### File: PmwScrolledCanvas.py
5865
5866
5867 class ScrolledCanvas(MegaWidget):
5868 def __init__(self, parent = None, **kw):
5869
5870 # Define the megawidget options.
5871
5872 optiondefs = (
5873 ('borderframe', 0, INITOPT),
5874 ('canvasmargin', 0, INITOPT),
5875 ('hscrollmode', 'dynamic', self._hscrollMode),
5876 ('labelmargin', 0, INITOPT),
5877 ('labelpos', None, INITOPT),
5878 ('scrollmargin', 2, INITOPT),
5879 ('usehullsize', 0, INITOPT),
5880 ('vscrollmode', 'dynamic', self._vscrollMode),
5881 )
5882 self.defineoptions(kw, optiondefs)
5883
5884 # Initialise the base class (after defining the options).
5885 MegaWidget.__init__(self, parent)
5886
5887 # Create the components.
5888 self.origInterior = MegaWidget.interior(self)
5889
5890 if self['usehullsize']:
5891 self.origInterior.grid_propagate(0)
5892
5893 if self['borderframe']:
5894 # Create a frame widget to act as the border of the canvas.
5895 self._borderframe = self.createcomponent('borderframe',
5896 (), None,
5897 Tkinter.Frame, (self.origInterior,),
5898 relief = 'sunken',
5899 borderwidth = 2,
5900 )
5901 self._borderframe.grid(row = 2, column = 2, sticky = 'news')
5902
5903 # Create the canvas widget.
5904 self._canvas = self.createcomponent('canvas',
5905 (), None,
5906 Tkinter.Canvas, (self._borderframe,),
5907 highlightthickness = 0,
5908 borderwidth = 0,
5909 )
5910 self._canvas.pack(fill = 'both', expand = 1)
5911 else:
5912 # Create the canvas widget.
5913 self._canvas = self.createcomponent('canvas',
5914 (), None,
5915 Tkinter.Canvas, (self.origInterior,),
5916 relief = 'sunken',
5917 borderwidth = 2,
5918 )
5919 self._canvas.grid(row = 2, column = 2, sticky = 'news')
5920
5921 self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0)
5922 self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0)
5923
5924 # Create the horizontal scrollbar
5925 self._horizScrollbar = self.createcomponent('horizscrollbar',
5926 (), 'Scrollbar',
5927 Tkinter.Scrollbar, (self.origInterior,),
5928 orient='horizontal',
5929 command=self._canvas.xview
5930 )
5931
5932 # Create the vertical scrollbar
5933 self._vertScrollbar = self.createcomponent('vertscrollbar',
5934 (), 'Scrollbar',
5935 Tkinter.Scrollbar, (self.origInterior,),
5936 orient='vertical',
5937 command=self._canvas.yview
5938 )
5939
5940 self.createlabel(self.origInterior, childCols = 3, childRows = 3)
5941
5942 # Initialise instance variables.
5943 self._horizScrollbarOn = 0
5944 self._vertScrollbarOn = 0
5945 self.scrollTimer = None
5946 self._scrollRecurse = 0
5947 self._horizScrollbarNeeded = 0
5948 self._vertScrollbarNeeded = 0
5949 self.setregionTimer = None
5950
5951 # Check keywords and initialise options.
5952 self.initialiseoptions()
5953
5954 def destroy(self):
5955 if self.scrollTimer is not None:
5956 self.after_cancel(self.scrollTimer)
5957 self.scrollTimer = None
5958 if self.setregionTimer is not None:
5959 self.after_cancel(self.setregionTimer)
5960 self.setregionTimer = None
5961 MegaWidget.destroy(self)
5962
5963 # ======================================================================
5964
5965 # Public methods.
5966
5967 def interior(self):
5968 return self._canvas
5969
5970 def resizescrollregion(self):
5971 if self.setregionTimer is None:
5972 self.setregionTimer = self.after_idle(self._setRegion)
5973
5974 # ======================================================================
5975
5976 # Configuration methods.
5977
5978 def _hscrollMode(self):
5979 # The horizontal scroll mode has been configured.
5980
5981 mode = self['hscrollmode']
5982
5983 if mode == 'static':
5984 if not self._horizScrollbarOn:
5985 self._toggleHorizScrollbar()
5986 elif mode == 'dynamic':
5987 if self._horizScrollbarNeeded != self._horizScrollbarOn:
5988 self._toggleHorizScrollbar()
5989 elif mode == 'none':
5990 if self._horizScrollbarOn:
5991 self._toggleHorizScrollbar()
5992 else:
5993 message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode
5994 raise ValueError(message)
5995
5996 self._configureScrollCommands()
5997
5998 def _vscrollMode(self):
5999 # The vertical scroll mode has been configured.
6000
6001 mode = self['vscrollmode']
6002
6003 if mode == 'static':
6004 if not self._vertScrollbarOn:
6005 self._toggleVertScrollbar()
6006 elif mode == 'dynamic':
6007 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6008 self._toggleVertScrollbar()
6009 elif mode == 'none':
6010 if self._vertScrollbarOn:
6011 self._toggleVertScrollbar()
6012 else:
6013 message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode
6014 raise ValueError(message)
6015
6016 self._configureScrollCommands()
6017
6018 # ======================================================================
6019
6020 # Private methods.
6021
6022 def _configureScrollCommands(self):
6023 # If both scrollmodes are not dynamic we can save a lot of
6024 # time by not having to create an idle job to handle the
6025 # scroll commands.
6026
6027 # Clean up previous scroll commands to prevent memory leak.
6028 tclCommandName = str(self._canvas.cget('xscrollcommand'))
6029 if tclCommandName != '':
6030 self._canvas.deletecommand(tclCommandName)
6031 tclCommandName = str(self._canvas.cget('yscrollcommand'))
6032 if tclCommandName != '':
6033 self._canvas.deletecommand(tclCommandName)
6034
6035 if self['hscrollmode'] == self['vscrollmode'] == 'dynamic':
6036 self._canvas.configure(
6037 xscrollcommand=self._scrollBothLater,
6038 yscrollcommand=self._scrollBothLater
6039 )
6040 else:
6041 self._canvas.configure(
6042 xscrollcommand=self._scrollXNow,
6043 yscrollcommand=self._scrollYNow
6044 )
6045
6046 def _scrollXNow(self, first, last):
6047 self._horizScrollbar.set(first, last)
6048 self._horizScrollbarNeeded = ((first, last) != ('0', '1'))
6049
6050 if self['hscrollmode'] == 'dynamic':
6051 if self._horizScrollbarNeeded != self._horizScrollbarOn:
6052 self._toggleHorizScrollbar()
6053
6054 def _scrollYNow(self, first, last):
6055 self._vertScrollbar.set(first, last)
6056 self._vertScrollbarNeeded = ((first, last) != ('0', '1'))
6057
6058 if self['vscrollmode'] == 'dynamic':
6059 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6060 self._toggleVertScrollbar()
6061
6062 def _scrollBothLater(self, first, last):
6063 # Called by the canvas to set the horizontal or vertical
6064 # scrollbar when it has scrolled or changed scrollregion.
6065
6066 if self.scrollTimer is None:
6067 self.scrollTimer = self.after_idle(self._scrollBothNow)
6068
6069 def _scrollBothNow(self):
6070 # This performs the function of _scrollXNow and _scrollYNow.
6071 # If one is changed, the other should be updated to match.
6072 self.scrollTimer = None
6073
6074 # Call update_idletasks to make sure that the containing frame
6075 # has been resized before we attempt to set the scrollbars.
6076 # Otherwise the scrollbars may be mapped/unmapped continuously.
6077 self._scrollRecurse = self._scrollRecurse + 1
6078 self.update_idletasks()
6079 self._scrollRecurse = self._scrollRecurse - 1
6080 if self._scrollRecurse != 0:
6081 return
6082
6083 xview = self._canvas.xview()
6084 yview = self._canvas.yview()
6085 self._horizScrollbar.set(xview[0], xview[1])
6086 self._vertScrollbar.set(yview[0], yview[1])
6087
6088 self._horizScrollbarNeeded = (xview != (0.0, 1.0))
6089 self._vertScrollbarNeeded = (yview != (0.0, 1.0))
6090
6091 # If both horizontal and vertical scrollmodes are dynamic and
6092 # currently only one scrollbar is mapped and both should be
6093 # toggled, then unmap the mapped scrollbar. This prevents a
6094 # continuous mapping and unmapping of the scrollbars.
6095 if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and
6096 self._horizScrollbarNeeded != self._horizScrollbarOn and
6097 self._vertScrollbarNeeded != self._vertScrollbarOn and
6098 self._vertScrollbarOn != self._horizScrollbarOn):
6099 if self._horizScrollbarOn:
6100 self._toggleHorizScrollbar()
6101 else:
6102 self._toggleVertScrollbar()
6103 return
6104
6105 if self['hscrollmode'] == 'dynamic':
6106 if self._horizScrollbarNeeded != self._horizScrollbarOn:
6107 self._toggleHorizScrollbar()
6108
6109 if self['vscrollmode'] == 'dynamic':
6110 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6111 self._toggleVertScrollbar()
6112
6113 def _toggleHorizScrollbar(self):
6114
6115 self._horizScrollbarOn = not self._horizScrollbarOn
6116
6117 interior = self.origInterior
6118 if self._horizScrollbarOn:
6119 self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news')
6120 interior.grid_rowconfigure(3, minsize = self['scrollmargin'])
6121 else:
6122 self._horizScrollbar.grid_forget()
6123 interior.grid_rowconfigure(3, minsize = 0)
6124
6125 def _toggleVertScrollbar(self):
6126
6127 self._vertScrollbarOn = not self._vertScrollbarOn
6128
6129 interior = self.origInterior
6130 if self._vertScrollbarOn:
6131 self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news')
6132 interior.grid_columnconfigure(3, minsize = self['scrollmargin'])
6133 else:
6134 self._vertScrollbar.grid_forget()
6135 interior.grid_columnconfigure(3, minsize = 0)
6136
6137 def _setRegion(self):
6138 self.setregionTimer = None
6139
6140 region = self._canvas.bbox('all')
6141 if region is not None:
6142 canvasmargin = self['canvasmargin']
6143 region = (region[0] - canvasmargin, region[1] - canvasmargin,
6144 region[2] + canvasmargin, region[3] + canvasmargin)
6145 self._canvas.configure(scrollregion = region)
6146
6147 # Need to explicitly forward this to override the stupid
6148 # (grid_)bbox method inherited from Tkinter.Frame.Grid.
6149 def bbox(self, *args):
6150 return self._canvas.bbox(*args)
6151
6152 forwardmethods(ScrolledCanvas, Tkinter.Canvas, '_canvas')
6153
6154 ######################################################################
6155 ### File: PmwScrolledField.py
6156
6157
6158 class ScrolledField(MegaWidget):
6159 def __init__(self, parent = None, **kw):
6160
6161 # Define the megawidget options.
6162
6163 optiondefs = (
6164 ('labelmargin', 0, INITOPT),
6165 ('labelpos', None, INITOPT),
6166 ('sticky', 'ew', INITOPT),
6167 ('text', '', self._text),
6168 )
6169 self.defineoptions(kw, optiondefs)
6170
6171 # Initialise the base class (after defining the options).
6172 MegaWidget.__init__(self, parent)
6173
6174 # Create the components.
6175 interior = self.interior()
6176 self._scrolledFieldEntry = self.createcomponent('entry',
6177 (), None,
6178 Tkinter.Entry, (interior,))
6179
6180 # Can't always use 'disabled', since this greys out text in Tk 8.4.2
6181 try:
6182 self._scrolledFieldEntry.configure(state = 'readonly')
6183 except Tkinter.TclError:
6184 self._scrolledFieldEntry.configure(state = 'disabled')
6185
6186 self._scrolledFieldEntry.grid(column=2, row=2, sticky=self['sticky'])
6187 interior.grid_columnconfigure(2, weight=1)
6188 interior.grid_rowconfigure(2, weight=1)
6189
6190 self.createlabel(interior)
6191
6192 # Check keywords and initialise options.
6193 self.initialiseoptions()
6194
6195 def _text(self):
6196 text = self['text']
6197 self._scrolledFieldEntry.configure(state = 'normal')
6198 self._scrolledFieldEntry.delete(0, 'end')
6199 self._scrolledFieldEntry.insert('end', text)
6200
6201 # Can't always use 'disabled', since this greys out text in Tk 8.4.2
6202 try:
6203 self._scrolledFieldEntry.configure(state = 'readonly')
6204 except Tkinter.TclError:
6205 self._scrolledFieldEntry.configure(state = 'disabled')
6206
6207 forwardmethods(ScrolledField, Tkinter.Entry, '_scrolledFieldEntry')
6208
6209 ######################################################################
6210 ### File: PmwScrolledFrame.py
6211
6212
6213 class ScrolledFrame(MegaWidget):
6214 def __init__(self, parent = None, **kw):
6215
6216 # Define the megawidget options.
6217
6218 optiondefs = (
6219 ('borderframe', 1, INITOPT),
6220 ('horizflex', 'fixed', self._horizflex),
6221 ('horizfraction', 0.05, INITOPT),
6222 ('hscrollmode', 'dynamic', self._hscrollMode),
6223 ('labelmargin', 0, INITOPT),
6224 ('labelpos', None, INITOPT),
6225 ('scrollmargin', 2, INITOPT),
6226 ('usehullsize', 0, INITOPT),
6227 ('vertflex', 'fixed', self._vertflex),
6228 ('vertfraction', 0.05, INITOPT),
6229 ('vscrollmode', 'dynamic', self._vscrollMode),
6230 )
6231 self.defineoptions(kw, optiondefs)
6232
6233 # Initialise the base class (after defining the options).
6234 MegaWidget.__init__(self, parent)
6235
6236 # Create the components.
6237 self.origInterior = MegaWidget.interior(self)
6238
6239 if self['usehullsize']:
6240 self.origInterior.grid_propagate(0)
6241
6242 if self['borderframe']:
6243 # Create a frame widget to act as the border of the clipper.
6244 self._borderframe = self.createcomponent('borderframe',
6245 (), None,
6246 Tkinter.Frame, (self.origInterior,),
6247 relief = 'sunken',
6248 borderwidth = 2,
6249 )
6250 self._borderframe.grid(row = 2, column = 2, sticky = 'news')
6251
6252 # Create the clipping window.
6253 self._clipper = self.createcomponent('clipper',
6254 (), None,
6255 Tkinter.Frame, (self._borderframe,),
6256 width = 400,
6257 height = 300,
6258 highlightthickness = 0,
6259 borderwidth = 0,
6260 )
6261 self._clipper.pack(fill = 'both', expand = 1)
6262 else:
6263 # Create the clipping window.
6264 self._clipper = self.createcomponent('clipper',
6265 (), None,
6266 Tkinter.Frame, (self.origInterior,),
6267 width = 400,
6268 height = 300,
6269 relief = 'sunken',
6270 borderwidth = 2,
6271 )
6272 self._clipper.grid(row = 2, column = 2, sticky = 'news')
6273
6274 self.origInterior.grid_rowconfigure(2, weight = 1, minsize = 0)
6275 self.origInterior.grid_columnconfigure(2, weight = 1, minsize = 0)
6276
6277 # Create the horizontal scrollbar
6278 self._horizScrollbar = self.createcomponent('horizscrollbar',
6279 (), 'Scrollbar',
6280 Tkinter.Scrollbar, (self.origInterior,),
6281 orient='horizontal',
6282 command=self.xview
6283 )
6284
6285 # Create the vertical scrollbar
6286 self._vertScrollbar = self.createcomponent('vertscrollbar',
6287 (), 'Scrollbar',
6288 Tkinter.Scrollbar, (self.origInterior,),
6289 orient='vertical',
6290 command=self.yview
6291 )
6292
6293 self.createlabel(self.origInterior, childCols = 3, childRows = 3)
6294
6295 # Initialise instance variables.
6296 self._horizScrollbarOn = 0
6297 self._vertScrollbarOn = 0
6298 self.scrollTimer = None
6299 self._scrollRecurse = 0
6300 self._horizScrollbarNeeded = 0
6301 self._vertScrollbarNeeded = 0
6302 self.startX = 0
6303 self.startY = 0
6304 self._flexoptions = ('fixed', 'expand', 'shrink', 'elastic')
6305
6306 # Create a frame in the clipper to contain the widgets to be
6307 # scrolled.
6308 self._frame = self.createcomponent('frame',
6309 (), None,
6310 Tkinter.Frame, (self._clipper,)
6311 )
6312
6313 # Whenever the clipping window or scrolled frame change size,
6314 # update the scrollbars.
6315 self._frame.bind('<Configure>', self._reposition)
6316 self._clipper.bind('<Configure>', self._reposition)
6317
6318 # Work around a bug in Tk where the value returned by the
6319 # scrollbar get() method is (0.0, 0.0, 0.0, 0.0) rather than
6320 # the expected 2-tuple. This occurs if xview() is called soon
6321 # after the ScrolledFrame has been created.
6322 self._horizScrollbar.set(0.0, 1.0)
6323 self._vertScrollbar.set(0.0, 1.0)
6324
6325 # Check keywords and initialise options.
6326 self.initialiseoptions()
6327
6328 def destroy(self):
6329 if self.scrollTimer is not None:
6330 self.after_cancel(self.scrollTimer)
6331 self.scrollTimer = None
6332 MegaWidget.destroy(self)
6333
6334 # ======================================================================
6335
6336 # Public methods.
6337
6338 def interior(self):
6339 return self._frame
6340
6341 # Set timer to call real reposition method, so that it is not
6342 # called multiple times when many things are reconfigured at the
6343 # same time.
6344 def reposition(self):
6345 if self.scrollTimer is None:
6346 self.scrollTimer = self.after_idle(self._scrollBothNow)
6347
6348 # Called when the user clicks in the horizontal scrollbar.
6349 # Calculates new position of frame then calls reposition() to
6350 # update the frame and the scrollbar.
6351 def xview(self, mode = None, value = None, units = None):
6352
6353 if isinstance(value, str):
6354 value = float(value)
6355 if mode is None:
6356 return self._horizScrollbar.get()
6357 elif mode == 'moveto':
6358 frameWidth = self._frame.winfo_reqwidth()
6359 self.startX = value * float(frameWidth)
6360 else: # mode == 'scroll'
6361 clipperWidth = self._clipper.winfo_width()
6362 if units == 'units':
6363 jump = int(clipperWidth * self['horizfraction'])
6364 else:
6365 jump = clipperWidth
6366 self.startX = self.startX + value * jump
6367
6368 self.reposition()
6369
6370 # Called when the user clicks in the vertical scrollbar.
6371 # Calculates new position of frame then calls reposition() to
6372 # update the frame and the scrollbar.
6373 def yview(self, mode = None, value = None, units = None):
6374
6375 if isinstance(value, str):
6376 value = float(value)
6377 if mode is None:
6378 return self._vertScrollbar.get()
6379 elif mode == 'moveto':
6380 frameHeight = self._frame.winfo_reqheight()
6381 self.startY = value * float(frameHeight)
6382 else: # mode == 'scroll'
6383 clipperHeight = self._clipper.winfo_height()
6384 if units == 'units':
6385 jump = int(clipperHeight * self['vertfraction'])
6386 else:
6387 jump = clipperHeight
6388 self.startY = self.startY + value * jump
6389
6390 self.reposition()
6391
6392 # ======================================================================
6393
6394 # Configuration methods.
6395
6396 def _hscrollMode(self):
6397 # The horizontal scroll mode has been configured.
6398
6399 mode = self['hscrollmode']
6400
6401 if mode == 'static':
6402 if not self._horizScrollbarOn:
6403 self._toggleHorizScrollbar()
6404 elif mode == 'dynamic':
6405 if self._horizScrollbarNeeded != self._horizScrollbarOn:
6406 self._toggleHorizScrollbar()
6407 elif mode == 'none':
6408 if self._horizScrollbarOn:
6409 self._toggleHorizScrollbar()
6410 else:
6411 message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode
6412 raise ValueError(message)
6413
6414 def _vscrollMode(self):
6415 # The vertical scroll mode has been configured.
6416
6417 mode = self['vscrollmode']
6418
6419 if mode == 'static':
6420 if not self._vertScrollbarOn:
6421 self._toggleVertScrollbar()
6422 elif mode == 'dynamic':
6423 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6424 self._toggleVertScrollbar()
6425 elif mode == 'none':
6426 if self._vertScrollbarOn:
6427 self._toggleVertScrollbar()
6428 else:
6429 message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode
6430 raise ValueError(message)
6431
6432 def _horizflex(self):
6433 # The horizontal flex mode has been configured.
6434
6435 flex = self['horizflex']
6436
6437 if flex not in self._flexoptions:
6438 message = 'bad horizflex option "%s": should be one of %s' % \
6439 (flex, str(self._flexoptions))
6440 raise ValueError(message)
6441
6442 self.reposition()
6443
6444 def _vertflex(self):
6445 # The vertical flex mode has been configured.
6446
6447 flex = self['vertflex']
6448
6449 if flex not in self._flexoptions:
6450 message = 'bad vertflex option "%s": should be one of %s' % \
6451 (flex, str(self._flexoptions))
6452 raise ValueError(message)
6453
6454 self.reposition()
6455
6456 # ======================================================================
6457
6458 # Private methods.
6459
6460 def _reposition(self, event):
6461 self.reposition()
6462
6463 def _getxview(self):
6464
6465 # Horizontal dimension.
6466 clipperWidth = self._clipper.winfo_width()
6467 frameWidth = self._frame.winfo_reqwidth()
6468 if frameWidth <= clipperWidth:
6469 # The scrolled frame is smaller than the clipping window.
6470
6471 self.startX = 0
6472 endScrollX = 1.0
6473
6474 if self['horizflex'] in ('expand', 'elastic'):
6475 relwidth = 1
6476 else:
6477 relwidth = ''
6478 else:
6479 # The scrolled frame is larger than the clipping window.
6480
6481 if self['horizflex'] in ('shrink', 'elastic'):
6482 self.startX = 0
6483 endScrollX = 1.0
6484 relwidth = 1
6485 else:
6486 if self.startX + clipperWidth > frameWidth:
6487 self.startX = frameWidth - clipperWidth
6488 endScrollX = 1.0
6489 else:
6490 if self.startX < 0:
6491 self.startX = 0
6492 endScrollX = (self.startX + clipperWidth) / float(frameWidth)
6493 relwidth = ''
6494
6495 # Position frame relative to clipper.
6496 self._frame.place(x = -self.startX, relwidth = relwidth)
6497 return (self.startX / float(frameWidth), endScrollX)
6498
6499 def _getyview(self):
6500
6501 # Vertical dimension.
6502 clipperHeight = self._clipper.winfo_height()
6503 frameHeight = self._frame.winfo_reqheight()
6504 if frameHeight <= clipperHeight:
6505 # The scrolled frame is smaller than the clipping window.
6506
6507 self.startY = 0
6508 endScrollY = 1.0
6509
6510 if self['vertflex'] in ('expand', 'elastic'):
6511 relheight = 1
6512 else:
6513 relheight = ''
6514 else:
6515 # The scrolled frame is larger than the clipping window.
6516
6517 if self['vertflex'] in ('shrink', 'elastic'):
6518 self.startY = 0
6519 endScrollY = 1.0
6520 relheight = 1
6521 else:
6522 if self.startY + clipperHeight > frameHeight:
6523 self.startY = frameHeight - clipperHeight
6524 endScrollY = 1.0
6525 else:
6526 if self.startY < 0:
6527 self.startY = 0
6528 endScrollY = (self.startY + clipperHeight) / float(frameHeight)
6529 relheight = ''
6530
6531 # Position frame relative to clipper.
6532 self._frame.place(y = -self.startY, relheight = relheight)
6533 return (self.startY / float(frameHeight), endScrollY)
6534
6535 # According to the relative geometries of the frame and the
6536 # clipper, reposition the frame within the clipper and reset the
6537 # scrollbars.
6538 def _scrollBothNow(self):
6539 self.scrollTimer = None
6540
6541 # Call update_idletasks to make sure that the containing frame
6542 # has been resized before we attempt to set the scrollbars.
6543 # Otherwise the scrollbars may be mapped/unmapped continuously.
6544 self._scrollRecurse = self._scrollRecurse + 1
6545 self.update_idletasks()
6546 self._scrollRecurse = self._scrollRecurse - 1
6547 if self._scrollRecurse != 0:
6548 return
6549
6550 xview = self._getxview()
6551 yview = self._getyview()
6552 self._horizScrollbar.set(xview[0], xview[1])
6553 self._vertScrollbar.set(yview[0], yview[1])
6554
6555 self._horizScrollbarNeeded = (xview != (0.0, 1.0))
6556 self._vertScrollbarNeeded = (yview != (0.0, 1.0))
6557
6558 # If both horizontal and vertical scrollmodes are dynamic and
6559 # currently only one scrollbar is mapped and both should be
6560 # toggled, then unmap the mapped scrollbar. This prevents a
6561 # continuous mapping and unmapping of the scrollbars.
6562 if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and
6563 self._horizScrollbarNeeded != self._horizScrollbarOn and
6564 self._vertScrollbarNeeded != self._vertScrollbarOn and
6565 self._vertScrollbarOn != self._horizScrollbarOn):
6566 if self._horizScrollbarOn:
6567 self._toggleHorizScrollbar()
6568 else:
6569 self._toggleVertScrollbar()
6570 return
6571
6572 if self['hscrollmode'] == 'dynamic':
6573 if self._horizScrollbarNeeded != self._horizScrollbarOn:
6574 self._toggleHorizScrollbar()
6575
6576 if self['vscrollmode'] == 'dynamic':
6577 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6578 self._toggleVertScrollbar()
6579
6580 def _toggleHorizScrollbar(self):
6581
6582 self._horizScrollbarOn = not self._horizScrollbarOn
6583
6584 interior = self.origInterior
6585 if self._horizScrollbarOn:
6586 self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news')
6587 interior.grid_rowconfigure(3, minsize = self['scrollmargin'])
6588 else:
6589 self._horizScrollbar.grid_forget()
6590 interior.grid_rowconfigure(3, minsize = 0)
6591
6592 def _toggleVertScrollbar(self):
6593
6594 self._vertScrollbarOn = not self._vertScrollbarOn
6595
6596 interior = self.origInterior
6597 if self._vertScrollbarOn:
6598 self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news')
6599 interior.grid_columnconfigure(3, minsize = self['scrollmargin'])
6600 else:
6601 self._vertScrollbar.grid_forget()
6602 interior.grid_columnconfigure(3, minsize = 0)
6603
6604 ######################################################################
6605 ### File: PmwScrolledListBox.py
6606 # Based on iwidgets2.2.0/scrolledlistbox.itk code.
6607
6608
6609
6610 class ScrolledListBox(MegaWidget):
6611 _classBindingsDefinedFor = 0
6612
6613 def __init__(self, parent = None, **kw):
6614
6615 # Define the megawidget options.
6616
6617 optiondefs = (
6618 ('dblclickcommand', None, None),
6619 ('hscrollmode', 'dynamic', self._hscrollMode),
6620 ('items', (), INITOPT),
6621 ('labelmargin', 0, INITOPT),
6622 ('labelpos', None, INITOPT),
6623 ('scrollmargin', 2, INITOPT),
6624 ('selectioncommand', None, None),
6625 ('usehullsize', 0, INITOPT),
6626 ('vscrollmode', 'dynamic', self._vscrollMode),
6627 )
6628 self.defineoptions(kw, optiondefs)
6629
6630 # Initialise the base class (after defining the options).
6631 MegaWidget.__init__(self, parent)
6632
6633 # Create the components.
6634 interior = self.interior()
6635
6636 if self['usehullsize']:
6637 interior.grid_propagate(0)
6638
6639 # Create the listbox widget.
6640 self._listbox = self.createcomponent('listbox',
6641 (), None,
6642 Tkinter.Listbox, (interior,))
6643 self._listbox.grid(row = 2, column = 2, sticky = 'news')
6644 interior.grid_rowconfigure(2, weight = 1, minsize = 0)
6645 interior.grid_columnconfigure(2, weight = 1, minsize = 0)
6646
6647 # Create the horizontal scrollbar
6648 self._horizScrollbar = self.createcomponent('horizscrollbar',
6649 (), 'Scrollbar',
6650 Tkinter.Scrollbar, (interior,),
6651 orient='horizontal',
6652 command=self._listbox.xview
6653 )
6654
6655 # Create the vertical scrollbar
6656 self._vertScrollbar = self.createcomponent('vertscrollbar',
6657 (), 'Scrollbar',
6658 Tkinter.Scrollbar, (interior,),
6659 orient='vertical',
6660 command=self._listbox.yview
6661 )
6662
6663 self.createlabel(interior, childCols = 3, childRows = 3)
6664
6665 # Add the items specified by the initialisation option.
6666 items = self['items']
6667 if not isinstance(items, tuple):
6668 items = tuple(items)
6669 if len(items) > 0:
6670 self._listbox.insert(*('end',) + items)
6671
6672 _registerScrolledList(self._listbox, self)
6673
6674 # Establish the special class bindings if not already done.
6675 # Also create bindings if the Tkinter default interpreter has
6676 # changed. Use Tkinter._default_root to create class
6677 # bindings, so that a reference to root is created by
6678 # bind_class rather than a reference to self, which would
6679 # prevent object cleanup.
6680 theTag = 'ScrolledListBoxTag'
6681 if ScrolledListBox._classBindingsDefinedFor != Tkinter._default_root:
6682 root = Tkinter._default_root
6683
6684 def doubleEvent(event):
6685 _handleEvent(event, 'double')
6686 def keyEvent(event):
6687 _handleEvent(event, 'key')
6688 def releaseEvent(event):
6689 _handleEvent(event, 'release')
6690
6691 # Bind space and return keys and button 1 to the selectioncommand.
6692 root.bind_class(theTag, '<Key-space>', keyEvent)
6693 root.bind_class(theTag, '<Key-Return>', keyEvent)
6694 root.bind_class(theTag, '<ButtonRelease-1>', releaseEvent)
6695
6696 # Bind double button 1 click to the dblclickcommand.
6697 root.bind_class(theTag, '<Double-ButtonRelease-1>', doubleEvent)
6698
6699 ScrolledListBox._classBindingsDefinedFor = root
6700
6701 bindtags = self._listbox.bindtags()
6702 self._listbox.bindtags(bindtags + (theTag,))
6703
6704 # Initialise instance variables.
6705 self._horizScrollbarOn = 0
6706 self._vertScrollbarOn = 0
6707 self.scrollTimer = None
6708 self._scrollRecurse = 0
6709 self._horizScrollbarNeeded = 0
6710 self._vertScrollbarNeeded = 0
6711
6712 # Check keywords and initialise options.
6713 self.initialiseoptions()
6714
6715 def destroy(self):
6716 if self.scrollTimer is not None:
6717 self.after_cancel(self.scrollTimer)
6718 self.scrollTimer = None
6719 _deregisterScrolledList(self._listbox)
6720 MegaWidget.destroy(self)
6721
6722 # ======================================================================
6723
6724 # Public methods.
6725
6726 def clear(self):
6727 self.setlist(())
6728
6729 def getcurselection(self):
6730 rtn = []
6731 for sel in self.curselection():
6732 rtn.append(self._listbox.get(sel))
6733 return tuple(rtn)
6734
6735 def getvalue(self):
6736 return self.getcurselection()
6737
6738 def setvalue(self, textOrList):
6739 self._listbox.selection_clear(0, 'end')
6740 listitems = list(self._listbox.get(0, 'end'))
6741 if isinstance(textOrList, str):
6742 if textOrList in listitems:
6743 self._listbox.selection_set(listitems.index(textOrList))
6744 else:
6745 raise ValueError('no such item "%s"' % textOrList)
6746 else:
6747 for item in textOrList:
6748 if item in listitems:
6749 self._listbox.selection_set(listitems.index(item))
6750 else:
6751 raise ValueError('no such item "%s"' % item)
6752
6753 def setlist(self, items):
6754 self._listbox.delete(0, 'end')
6755 if len(items) > 0:
6756 if not isinstance(items, tuple):
6757 items = tuple(items)
6758 self._listbox.insert(*(0,) + items)
6759
6760 # Override Tkinter.Listbox get method, so that if it is called with
6761 # no arguments, return all list elements (consistent with other widgets).
6762 def get(self, first=None, last=None):
6763 if first is None:
6764 return self._listbox.get(0, 'end')
6765 else:
6766 return self._listbox.get(first, last)
6767
6768 # ======================================================================
6769
6770 # Configuration methods.
6771
6772 def _hscrollMode(self):
6773 # The horizontal scroll mode has been configured.
6774
6775 mode = self['hscrollmode']
6776
6777 if mode == 'static':
6778 if not self._horizScrollbarOn:
6779 self._toggleHorizScrollbar()
6780 elif mode == 'dynamic':
6781 if self._horizScrollbarNeeded != self._horizScrollbarOn:
6782 self._toggleHorizScrollbar()
6783 elif mode == 'none':
6784 if self._horizScrollbarOn:
6785 self._toggleHorizScrollbar()
6786 else:
6787 message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode
6788 raise ValueError(message)
6789
6790 self._configureScrollCommands()
6791
6792 def _vscrollMode(self):
6793 # The vertical scroll mode has been configured.
6794
6795 mode = self['vscrollmode']
6796
6797 if mode == 'static':
6798 if not self._vertScrollbarOn:
6799 self._toggleVertScrollbar()
6800 elif mode == 'dynamic':
6801 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6802 self._toggleVertScrollbar()
6803 elif mode == 'none':
6804 if self._vertScrollbarOn:
6805 self._toggleVertScrollbar()
6806 else:
6807 message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode
6808 raise ValueError(message)
6809
6810 self._configureScrollCommands()
6811
6812 # ======================================================================
6813
6814 # Private methods.
6815
6816 def _configureScrollCommands(self):
6817 # If both scrollmodes are not dynamic we can save a lot of
6818 # time by not having to create an idle job to handle the
6819 # scroll commands.
6820
6821 # Clean up previous scroll commands to prevent memory leak.
6822 tclCommandName = str(self._listbox.cget('xscrollcommand'))
6823 if tclCommandName != '':
6824 self._listbox.deletecommand(tclCommandName)
6825 tclCommandName = str(self._listbox.cget('yscrollcommand'))
6826 if tclCommandName != '':
6827 self._listbox.deletecommand(tclCommandName)
6828
6829 if self['hscrollmode'] == self['vscrollmode'] == 'dynamic':
6830 self._listbox.configure(
6831 xscrollcommand=self._scrollBothLater,
6832 yscrollcommand=self._scrollBothLater
6833 )
6834 else:
6835 self._listbox.configure(
6836 xscrollcommand=self._scrollXNow,
6837 yscrollcommand=self._scrollYNow
6838 )
6839
6840 def _scrollXNow(self, first, last):
6841 self._horizScrollbar.set(first, last)
6842 self._horizScrollbarNeeded = ((first, last) != ('0', '1'))
6843
6844 if self['hscrollmode'] == 'dynamic':
6845 if self._horizScrollbarNeeded != self._horizScrollbarOn:
6846 self._toggleHorizScrollbar()
6847
6848 def _scrollYNow(self, first, last):
6849 self._vertScrollbar.set(first, last)
6850 self._vertScrollbarNeeded = ((first, last) != ('0', '1'))
6851
6852 if self['vscrollmode'] == 'dynamic':
6853 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6854 self._toggleVertScrollbar()
6855
6856 def _scrollBothLater(self, first, last):
6857 # Called by the listbox to set the horizontal or vertical
6858 # scrollbar when it has scrolled or changed size or contents.
6859
6860 if self.scrollTimer is None:
6861 self.scrollTimer = self.after_idle(self._scrollBothNow)
6862
6863 def _scrollBothNow(self):
6864 # This performs the function of _scrollXNow and _scrollYNow.
6865 # If one is changed, the other should be updated to match.
6866 self.scrollTimer = None
6867
6868 # Call update_idletasks to make sure that the containing frame
6869 # has been resized before we attempt to set the scrollbars.
6870 # Otherwise the scrollbars may be mapped/unmapped continuously.
6871 self._scrollRecurse = self._scrollRecurse + 1
6872 self.update_idletasks()
6873 self._scrollRecurse = self._scrollRecurse - 1
6874 if self._scrollRecurse != 0:
6875 return
6876
6877 xview = self._listbox.xview()
6878 yview = self._listbox.yview()
6879 self._horizScrollbar.set(xview[0], xview[1])
6880 self._vertScrollbar.set(yview[0], yview[1])
6881
6882 self._horizScrollbarNeeded = (xview != (0.0, 1.0))
6883 self._vertScrollbarNeeded = (yview != (0.0, 1.0))
6884
6885 # If both horizontal and vertical scrollmodes are dynamic and
6886 # currently only one scrollbar is mapped and both should be
6887 # toggled, then unmap the mapped scrollbar. This prevents a
6888 # continuous mapping and unmapping of the scrollbars.
6889 if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and
6890 self._horizScrollbarNeeded != self._horizScrollbarOn and
6891 self._vertScrollbarNeeded != self._vertScrollbarOn and
6892 self._vertScrollbarOn != self._horizScrollbarOn):
6893 if self._horizScrollbarOn:
6894 self._toggleHorizScrollbar()
6895 else:
6896 self._toggleVertScrollbar()
6897 return
6898
6899 if self['hscrollmode'] == 'dynamic':
6900 if self._horizScrollbarNeeded != self._horizScrollbarOn:
6901 self._toggleHorizScrollbar()
6902
6903 if self['vscrollmode'] == 'dynamic':
6904 if self._vertScrollbarNeeded != self._vertScrollbarOn:
6905 self._toggleVertScrollbar()
6906
6907 def _toggleHorizScrollbar(self):
6908
6909 self._horizScrollbarOn = not self._horizScrollbarOn
6910
6911 interior = self.interior()
6912 if self._horizScrollbarOn:
6913 self._horizScrollbar.grid(row = 4, column = 2, sticky = 'news')
6914 interior.grid_rowconfigure(3, minsize = self['scrollmargin'])
6915 else:
6916 self._horizScrollbar.grid_forget()
6917 interior.grid_rowconfigure(3, minsize = 0)
6918
6919 def _toggleVertScrollbar(self):
6920
6921 self._vertScrollbarOn = not self._vertScrollbarOn
6922
6923 interior = self.interior()
6924 if self._vertScrollbarOn:
6925 self._vertScrollbar.grid(row = 2, column = 4, sticky = 'news')
6926 interior.grid_columnconfigure(3, minsize = self['scrollmargin'])
6927 else:
6928 self._vertScrollbar.grid_forget()
6929 interior.grid_columnconfigure(3, minsize = 0)
6930
6931 def _handleEvent(self, event, eventType):
6932 if eventType == 'double':
6933 command = self['dblclickcommand']
6934 elif eventType == 'key':
6935 command = self['selectioncommand']
6936 else: #eventType == 'release'
6937 # Do not execute the command if the mouse was released
6938 # outside the listbox.
6939 if (event.x < 0 or self._listbox.winfo_width() <= event.x or
6940 event.y < 0 or self._listbox.winfo_height() <= event.y):
6941 return
6942
6943 command = self['selectioncommand']
6944
6945 if hasattr(command, '__call__'):
6946 command()
6947
6948 # Need to explicitly forward this to override the stupid
6949 # (grid_)size method inherited from Tkinter.Frame.Grid.
6950 def size(self):
6951 return self._listbox.size()
6952
6953 # Need to explicitly forward this to override the stupid
6954 # (grid_)bbox method inherited from Tkinter.Frame.Grid.
6955 def bbox(self, index):
6956 return self._listbox.bbox(index)
6957
6958 forwardmethods(ScrolledListBox, Tkinter.Listbox, '_listbox')
6959
6960 # ======================================================================
6961
6962 _listboxCache = {}
6963
6964 def _registerScrolledList(listbox, scrolledList):
6965 # Register an ScrolledList widget for a Listbox widget
6966
6967 _listboxCache[listbox] = scrolledList
6968
6969 def _deregisterScrolledList(listbox):
6970 # Deregister a Listbox widget
6971 del _listboxCache[listbox]
6972
6973 def _handleEvent(event, eventType):
6974 # Forward events for a Listbox to it's ScrolledListBox
6975
6976 # A binding earlier in the bindtags list may have destroyed the
6977 # megawidget, so need to check.
6978 if event.widget in _listboxCache:
6979 _listboxCache[event.widget]._handleEvent(event, eventType)
6980
6981 ######################################################################
6982 ### File: PmwScrolledText.py
6983 # Based on iwidgets2.2.0/scrolledtext.itk code.
6984
6985
6986
6987 class ScrolledText(MegaWidget):
6988 def __init__(self, parent = None, **kw):
6989
6990 # Define the megawidget options.
6991
6992 optiondefs = (
6993 ('borderframe', 0, INITOPT),
6994 ('columnheader', 0, INITOPT),
6995 ('hscrollmode', 'dynamic', self._hscrollMode),
6996 ('labelmargin', 0, INITOPT),
6997 ('labelpos', None, INITOPT),
6998 ('rowcolumnheader',0, INITOPT),
6999 ('rowheader', 0, INITOPT),
7000 ('scrollmargin', 2, INITOPT),
7001 ('usehullsize', 0, INITOPT),
7002 ('vscrollmode', 'dynamic', self._vscrollMode),
7003 )
7004 self.defineoptions(kw, optiondefs)
7005
7006 # Initialise the base class (after defining the options).
7007 MegaWidget.__init__(self, parent)
7008
7009 # Create the components.
7010 interior = self.interior()
7011
7012 if self['usehullsize']:
7013 interior.grid_propagate(0)
7014
7015 if self['borderframe']:
7016 # Create a frame widget to act as the border of the text
7017 # widget. Later, pack the text widget so that it fills
7018 # the frame. This avoids a problem in Tk, where window
7019 # items in a text widget may overlap the border of the
7020 # text widget.
7021 self._borderframe = self.createcomponent('borderframe',
7022 (), None,
7023 Tkinter.Frame, (interior,),
7024 relief = 'sunken',
7025 borderwidth = 2,
7026 )
7027 self._borderframe.grid(row = 4, column = 4, sticky = 'news')
7028
7029 # Create the text widget.
7030 self._textbox = self.createcomponent('text',
7031 (), None,
7032 Tkinter.Text, (self._borderframe,),
7033 highlightthickness = 0,
7034 borderwidth = 0,
7035 )
7036 self._textbox.pack(fill = 'both', expand = 1)
7037
7038 bw = self._borderframe.cget('borderwidth'),
7039 ht = self._borderframe.cget('highlightthickness'),
7040 else:
7041 # Create the text widget.
7042 self._textbox = self.createcomponent('text',
7043 (), None,
7044 Tkinter.Text, (interior,),
7045 )
7046 self._textbox.grid(row = 4, column = 4, sticky = 'news')
7047
7048 bw = self._textbox.cget('borderwidth'),
7049 ht = self._textbox.cget('highlightthickness'),
7050
7051 # Create the header text widgets
7052 if self['columnheader']:
7053 self._columnheader = self.createcomponent('columnheader',
7054 (), 'Header',
7055 Tkinter.Text, (interior,),
7056 height=1,
7057 wrap='none',
7058 borderwidth = bw,
7059 highlightthickness = ht,
7060 )
7061 self._columnheader.grid(row = 2, column = 4, sticky = 'ew')
7062 self._columnheader.configure(
7063 xscrollcommand = self._columnheaderscrolled)
7064
7065 if self['rowheader']:
7066 self._rowheader = self.createcomponent('rowheader',
7067 (), 'Header',
7068 Tkinter.Text, (interior,),
7069 wrap='none',
7070 borderwidth = bw,
7071 highlightthickness = ht,
7072 )
7073 self._rowheader.grid(row = 4, column = 2, sticky = 'ns')
7074 self._rowheader.configure(
7075 yscrollcommand = self._rowheaderscrolled)
7076
7077 if self['rowcolumnheader']:
7078 self._rowcolumnheader = self.createcomponent('rowcolumnheader',
7079 (), 'Header',
7080 Tkinter.Text, (interior,),
7081 height=1,
7082 wrap='none',
7083 borderwidth = bw,
7084 highlightthickness = ht,
7085 )
7086 self._rowcolumnheader.grid(row = 2, column = 2, sticky = 'nsew')
7087
7088 interior.grid_rowconfigure(4, weight = 1, minsize = 0)
7089 interior.grid_columnconfigure(4, weight = 1, minsize = 0)
7090
7091 # Create the horizontal scrollbar
7092 self._horizScrollbar = self.createcomponent('horizscrollbar',
7093 (), 'Scrollbar',
7094 Tkinter.Scrollbar, (interior,),
7095 orient='horizontal',
7096 command=self._textbox.xview
7097 )
7098
7099 # Create the vertical scrollbar
7100 self._vertScrollbar = self.createcomponent('vertscrollbar',
7101 (), 'Scrollbar',
7102 Tkinter.Scrollbar, (interior,),
7103 orient='vertical',
7104 command=self._textbox.yview
7105 )
7106
7107 self.createlabel(interior, childCols = 5, childRows = 5)
7108
7109 # Initialise instance variables.
7110 self._horizScrollbarOn = 0
7111 self._vertScrollbarOn = 0
7112 self.scrollTimer = None
7113 self._scrollRecurse = 0
7114 self._horizScrollbarNeeded = 0
7115 self._vertScrollbarNeeded = 0
7116 self._textWidth = None
7117
7118 # These four variables avoid an infinite loop caused by the
7119 # row or column header's scrollcommand causing the main text
7120 # widget's scrollcommand to be called and vice versa.
7121 self._textboxLastX = None
7122 self._textboxLastY = None
7123 self._columnheaderLastX = None
7124 self._rowheaderLastY = None
7125
7126 # Check keywords and initialise options.
7127 self.initialiseoptions()
7128
7129 def destroy(self):
7130 if self.scrollTimer is not None:
7131 self.after_cancel(self.scrollTimer)
7132 self.scrollTimer = None
7133 MegaWidget.destroy(self)
7134
7135 # ======================================================================
7136
7137 # Public methods.
7138
7139 def clear(self):
7140 self.settext('')
7141
7142 def importfile(self, fileName, where = 'end'):
7143 file = open(fileName, 'r')
7144 self._textbox.insert(where, file.read())
7145 file.close()
7146
7147 def exportfile(self, fileName):
7148 file = open(fileName, 'w')
7149 file.write(self._textbox.get('1.0', 'end'))
7150 file.close()
7151
7152 def settext(self, text):
7153 disabled = (str(self._textbox.cget('state')) == 'disabled')
7154 if disabled:
7155 self._textbox.configure(state='normal')
7156 self._textbox.delete('0.0', 'end')
7157 self._textbox.insert('end', text)
7158 if disabled:
7159 self._textbox.configure(state='disabled')
7160
7161 # Override Tkinter.Text get method, so that if it is called with
7162 # no arguments, return all text (consistent with other widgets).
7163 def get(self, first=None, last=None):
7164 if first is None:
7165 return self._textbox.get('1.0', 'end')
7166 else:
7167 return self._textbox.get(first, last)
7168
7169 def getvalue(self):
7170 return self.get()
7171
7172 def setvalue(self, text):
7173 return self.settext(text)
7174
7175 def appendtext(self, text):
7176 oldTop, oldBottom = self._textbox.yview()
7177
7178 disabled = (str(self._textbox.cget('state')) == 'disabled')
7179 if disabled:
7180 self._textbox.configure(state='normal')
7181 self._textbox.insert('end', text)
7182 if disabled:
7183 self._textbox.configure(state='disabled')
7184
7185 if oldBottom == 1.0:
7186 self._textbox.yview('moveto', 1.0)
7187
7188 # ======================================================================
7189
7190 # Configuration methods.
7191
7192 def _hscrollMode(self):
7193 # The horizontal scroll mode has been configured.
7194
7195 mode = self['hscrollmode']
7196
7197 if mode == 'static':
7198 if not self._horizScrollbarOn:
7199 self._toggleHorizScrollbar()
7200 elif mode == 'dynamic':
7201 if self._horizScrollbarNeeded != self._horizScrollbarOn:
7202 self._toggleHorizScrollbar()
7203 elif mode == 'none':
7204 if self._horizScrollbarOn:
7205 self._toggleHorizScrollbar()
7206 else:
7207 message = 'bad hscrollmode option "%s": should be static, dynamic, or none' % mode
7208 raise ValueError(message)
7209
7210 self._configureScrollCommands()
7211
7212 def _vscrollMode(self):
7213 # The vertical scroll mode has been configured.
7214
7215 mode = self['vscrollmode']
7216
7217 if mode == 'static':
7218 if not self._vertScrollbarOn:
7219 self._toggleVertScrollbar()
7220 elif mode == 'dynamic':
7221 if self._vertScrollbarNeeded != self._vertScrollbarOn:
7222 self._toggleVertScrollbar()
7223 elif mode == 'none':
7224 if self._vertScrollbarOn:
7225 self._toggleVertScrollbar()
7226 else:
7227 message = 'bad vscrollmode option "%s": should be static, dynamic, or none' % mode
7228 raise ValueError(message)
7229
7230 self._configureScrollCommands()
7231
7232 # ======================================================================
7233
7234 # Private methods.
7235
7236 def _configureScrollCommands(self):
7237 # If both scrollmodes are not dynamic we can save a lot of
7238 # time by not having to create an idle job to handle the
7239 # scroll commands.
7240
7241 # Clean up previous scroll commands to prevent memory leak.
7242 tclCommandName = str(self._textbox.cget('xscrollcommand'))
7243 if tclCommandName != '':
7244 self._textbox.deletecommand(tclCommandName)
7245 tclCommandName = str(self._textbox.cget('yscrollcommand'))
7246 if tclCommandName != '':
7247 self._textbox.deletecommand(tclCommandName)
7248
7249 if self['hscrollmode'] == self['vscrollmode'] == 'dynamic':
7250 self._textbox.configure(
7251 xscrollcommand=self._scrollBothLater,
7252 yscrollcommand=self._scrollBothLater
7253 )
7254 else:
7255 self._textbox.configure(
7256 xscrollcommand=self._scrollXNow,
7257 yscrollcommand=self._scrollYNow
7258 )
7259
7260 def _scrollXNow(self, first, last):
7261 self._horizScrollbar.set(first, last)
7262 self._horizScrollbarNeeded = ((first, last) != ('0', '1'))
7263
7264 # This code is the same as in _scrollBothNow. Keep it that way.
7265 if self['hscrollmode'] == 'dynamic':
7266 currentWidth = self._textbox.winfo_width()
7267 if self._horizScrollbarNeeded != self._horizScrollbarOn:
7268 if self._horizScrollbarNeeded or \
7269 self._textWidth != currentWidth:
7270 self._toggleHorizScrollbar()
7271 self._textWidth = currentWidth
7272
7273 if self['columnheader']:
7274 if self._columnheaderLastX != first:
7275 self._columnheaderLastX = first
7276 self._columnheader.xview('moveto', first)
7277
7278 def _scrollYNow(self, first, last):
7279 if first == '0' and last == '0':
7280 return
7281 self._vertScrollbar.set(first, last)
7282 self._vertScrollbarNeeded = ((first, last) != ('0', '1'))
7283
7284 if self['vscrollmode'] == 'dynamic':
7285 if self._vertScrollbarNeeded != self._vertScrollbarOn:
7286 self._toggleVertScrollbar()
7287
7288 if self['rowheader']:
7289 if self._rowheaderLastY != first:
7290 self._rowheaderLastY = first
7291 self._rowheader.yview('moveto', first)
7292
7293 def _scrollBothLater(self, first, last):
7294 # Called by the text widget to set the horizontal or vertical
7295 # scrollbar when it has scrolled or changed size or contents.
7296
7297 if self.scrollTimer is None:
7298 self.scrollTimer = self.after_idle(self._scrollBothNow)
7299
7300 def _scrollBothNow(self):
7301 # This performs the function of _scrollXNow and _scrollYNow.
7302 # If one is changed, the other should be updated to match.
7303 self.scrollTimer = None
7304
7305 # Call update_idletasks to make sure that the containing frame
7306 # has been resized before we attempt to set the scrollbars.
7307 # Otherwise the scrollbars may be mapped/unmapped continuously.
7308 self._scrollRecurse = self._scrollRecurse + 1
7309 self.update_idletasks()
7310 self._scrollRecurse = self._scrollRecurse - 1
7311 if self._scrollRecurse != 0:
7312 return
7313
7314 xview = self._textbox.xview()
7315 yview = self._textbox.yview()
7316
7317 # The text widget returns a yview of (0.0, 0.0) just after it
7318 # has been created. Ignore this.
7319 if yview == (0.0, 0.0):
7320 return
7321
7322 if self['columnheader']:
7323 if self._columnheaderLastX != xview[0]:
7324 self._columnheaderLastX = xview[0]
7325 self._columnheader.xview('moveto', xview[0])
7326 if self['rowheader']:
7327 if self._rowheaderLastY != yview[0]:
7328 self._rowheaderLastY = yview[0]
7329 self._rowheader.yview('moveto', yview[0])
7330
7331 self._horizScrollbar.set(xview[0], xview[1])
7332 self._vertScrollbar.set(yview[0], yview[1])
7333
7334 self._horizScrollbarNeeded = (xview != (0.0, 1.0))
7335 self._vertScrollbarNeeded = (yview != (0.0, 1.0))
7336
7337 # If both horizontal and vertical scrollmodes are dynamic and
7338 # currently only one scrollbar is mapped and both should be
7339 # toggled, then unmap the mapped scrollbar. This prevents a
7340 # continuous mapping and unmapping of the scrollbars.
7341 if (self['hscrollmode'] == self['vscrollmode'] == 'dynamic' and
7342 self._horizScrollbarNeeded != self._horizScrollbarOn and
7343 self._vertScrollbarNeeded != self._vertScrollbarOn and
7344 self._vertScrollbarOn != self._horizScrollbarOn):
7345 if self._horizScrollbarOn:
7346 self._toggleHorizScrollbar()
7347 else:
7348 self._toggleVertScrollbar()
7349 return
7350
7351 if self['hscrollmode'] == 'dynamic':
7352
7353 # The following test is done to prevent continuous
7354 # mapping and unmapping of the horizontal scrollbar.
7355 # This may occur when some event (scrolling, resizing
7356 # or text changes) modifies the displayed text such
7357 # that the bottom line in the window is the longest
7358 # line displayed. If this causes the horizontal
7359 # scrollbar to be mapped, the scrollbar may "cover up"
7360 # the bottom line, which would mean that the scrollbar
7361 # is no longer required. If the scrollbar is then
7362 # unmapped, the bottom line will then become visible
7363 # again, which would cause the scrollbar to be mapped
7364 # again, and so on...
7365 #
7366 # The idea is that, if the width of the text widget
7367 # has not changed and the scrollbar is currently
7368 # mapped, then do not unmap the scrollbar even if it
7369 # is no longer required. This means that, during
7370 # normal scrolling of the text, once the horizontal
7371 # scrollbar has been mapped it will not be unmapped
7372 # (until the width of the text widget changes).
7373
7374 currentWidth = self._textbox.winfo_width()
7375 if self._horizScrollbarNeeded != self._horizScrollbarOn:
7376 if self._horizScrollbarNeeded or \
7377 self._textWidth != currentWidth:
7378 self._toggleHorizScrollbar()
7379 self._textWidth = currentWidth
7380
7381 if self['vscrollmode'] == 'dynamic':
7382 if self._vertScrollbarNeeded != self._vertScrollbarOn:
7383 self._toggleVertScrollbar()
7384
7385 def _columnheaderscrolled(self, first, last):
7386 if self._textboxLastX != first:
7387 self._textboxLastX = first
7388 self._textbox.xview('moveto', first)
7389
7390 def _rowheaderscrolled(self, first, last):
7391 if self._textboxLastY != first:
7392 self._textboxLastY = first
7393 self._textbox.yview('moveto', first)
7394
7395 def _toggleHorizScrollbar(self):
7396
7397 self._horizScrollbarOn = not self._horizScrollbarOn
7398
7399 interior = self.interior()
7400 if self._horizScrollbarOn:
7401 self._horizScrollbar.grid(row = 6, column = 4, sticky = 'news')
7402 interior.grid_rowconfigure(5, minsize = self['scrollmargin'])
7403 else:
7404 self._horizScrollbar.grid_forget()
7405 interior.grid_rowconfigure(5, minsize = 0)
7406
7407 def _toggleVertScrollbar(self):
7408
7409 self._vertScrollbarOn = not self._vertScrollbarOn
7410
7411 interior = self.interior()
7412 if self._vertScrollbarOn:
7413 self._vertScrollbar.grid(row = 4, column = 6, sticky = 'news')
7414 interior.grid_columnconfigure(5, minsize = self['scrollmargin'])
7415 else:
7416 self._vertScrollbar.grid_forget()
7417 interior.grid_columnconfigure(5, minsize = 0)
7418
7419 # Need to explicitly forward this to override the stupid
7420 # (grid_)bbox method inherited from Tkinter.Frame.Grid.
7421 def bbox(self, index):
7422 return self._textbox.bbox(index)
7423
7424 forwardmethods(ScrolledText, Tkinter.Text, '_textbox')
7425
7426 ######################################################################
7427 ### File: PmwHistoryText.py
7428
7429
7430 _ORIGINAL = 0
7431 _MODIFIED = 1
7432 _DISPLAY = 2
7433
7434 class HistoryText(ScrolledText):
7435
7436 def __init__(self, parent = None, **kw):
7437
7438 # Define the megawidget options.
7439 optiondefs = (
7440 ('compressany', 1, None),
7441 ('compresstail', 1, None),
7442 ('historycommand', None, None),
7443 )
7444 self.defineoptions(kw, optiondefs)
7445
7446 # Initialise the base class (after defining the options).
7447 ScrolledText.__init__(self, parent)
7448
7449 # Initialise instance variables.
7450 self._list = []
7451 self._currIndex = 0
7452 self._pastIndex = None
7453 self._lastIndex = 0 # pointer to end of history list
7454
7455 # Check keywords and initialise options.
7456 self.initialiseoptions()
7457
7458 def addhistory(self):
7459 text = self.get()
7460 if text[-1] == '\n':
7461 text = text[:-1]
7462
7463 if len(self._list) == 0:
7464 # This is the first history entry. Add it.
7465 self._list.append([text, text, _MODIFIED])
7466 return
7467
7468 currentEntry = self._list[self._currIndex]
7469 if text == currentEntry[_ORIGINAL]:
7470 # The current history entry has not been modified. Check if
7471 # we need to add it again.
7472
7473 if self['compresstail'] and self._currIndex == self._lastIndex:
7474 return
7475
7476 if self['compressany']:
7477 return
7478
7479 # Undo any changes for the current history entry, since they
7480 # will now be available in the new entry.
7481 currentEntry[_MODIFIED] = currentEntry[_ORIGINAL]
7482
7483 historycommand = self['historycommand']
7484 if self._currIndex == self._lastIndex:
7485 # The last history entry is currently being displayed,
7486 # so disable the special meaning of the 'Next' button.
7487 self._pastIndex = None
7488 nextState = 'disabled'
7489 else:
7490 # A previous history entry is currently being displayed,
7491 # so allow the 'Next' button to go to the entry after this one.
7492 self._pastIndex = self._currIndex
7493 nextState = 'normal'
7494 if hasattr(historycommand, '__call__'):
7495 historycommand('normal', nextState)
7496
7497 # Create the new history entry.
7498 self._list.append([text, text, _MODIFIED])
7499
7500 # Move the pointer into the history entry list to the end.
7501 self._lastIndex = self._lastIndex + 1
7502 self._currIndex = self._lastIndex
7503
7504 def next(self):
7505 if self._currIndex == self._lastIndex and self._pastIndex is None:
7506 self.bell()
7507 else:
7508 self._modifyDisplay('next')
7509
7510 def prev(self):
7511 self._pastIndex = None
7512 if self._currIndex == 0:
7513 self.bell()
7514 else:
7515 self._modifyDisplay('prev')
7516
7517 def undo(self):
7518 if len(self._list) != 0:
7519 self._modifyDisplay('undo')
7520
7521 def redo(self):
7522 if len(self._list) != 0:
7523 self._modifyDisplay('redo')
7524
7525 def gethistory(self):
7526 return self._list
7527
7528 def _modifyDisplay(self, command):
7529 # Modify the display to show either the next or previous
7530 # history entry (next, prev) or the original or modified
7531 # version of the current history entry (undo, redo).
7532
7533 # Save the currently displayed text.
7534 currentText = self.get()
7535 if currentText[-1] == '\n':
7536 currentText = currentText[:-1]
7537
7538 currentEntry = self._list[self._currIndex]
7539 if currentEntry[_DISPLAY] == _MODIFIED:
7540 currentEntry[_MODIFIED] = currentText
7541 elif currentEntry[_ORIGINAL] != currentText:
7542 currentEntry[_MODIFIED] = currentText
7543 if command in ('next', 'prev'):
7544 currentEntry[_DISPLAY] = _MODIFIED
7545
7546 if command in ('next', 'prev'):
7547 prevstate = 'normal'
7548 nextstate = 'normal'
7549 if command == 'next':
7550 if self._pastIndex is not None:
7551 self._currIndex = self._pastIndex
7552 self._pastIndex = None
7553 self._currIndex = self._currIndex + 1
7554 if self._currIndex == self._lastIndex:
7555 nextstate = 'disabled'
7556 elif command == 'prev':
7557 self._currIndex = self._currIndex - 1
7558 if self._currIndex == 0:
7559 prevstate = 'disabled'
7560 historycommand = self['historycommand']
7561 if hasattr(historycommand, '__call__'):
7562 historycommand(prevstate, nextstate)
7563 currentEntry = self._list[self._currIndex]
7564 else:
7565 if command == 'undo':
7566 currentEntry[_DISPLAY] = _ORIGINAL
7567 elif command == 'redo':
7568 currentEntry[_DISPLAY] = _MODIFIED
7569
7570 # Display the new text.
7571 self.delete('1.0', 'end')
7572 self.insert('end', currentEntry[currentEntry[_DISPLAY]])
7573
7574 ######################################################################
7575 ### File: PmwSelectionDialog.py
7576 # Not Based on iwidgets version.
7577
7578
7579
7580 class SelectionDialog(Dialog):
7581 # Dialog window with selection list.
7582
7583 # Dialog window displaying a list and requesting the user to
7584 # select one.
7585
7586 def __init__(self, parent = None, **kw):
7587 # Define the megawidget options.
7588
7589 optiondefs = (
7590 ('borderx', 10, INITOPT),
7591 ('bordery', 10, INITOPT),
7592 )
7593 self.defineoptions(kw, optiondefs)
7594
7595 # Initialise the base class (after defining the options).
7596 Dialog.__init__(self, parent)
7597
7598 # Create the components.
7599 interior = self.interior()
7600 aliases = (
7601 ('listbox', 'scrolledlist_listbox'),
7602 ('label', 'scrolledlist_label'),
7603 )
7604 self._list = self.createcomponent('scrolledlist',
7605 aliases, None,
7606 ScrolledListBox, (interior,),
7607 dblclickcommand = self.invoke)
7608 self._list.pack(side='top', expand='true', fill='both',
7609 padx = self['borderx'], pady = self['bordery'])
7610
7611 if 'activatecommand' not in kw:
7612 # Whenever this dialog is activated, set the focus to the
7613 # ScrolledListBox's listbox widget.
7614 listbox = self.component('listbox')
7615 self.configure(activatecommand = listbox.focus_set)
7616
7617 # Check keywords and initialise options.
7618 self.initialiseoptions()
7619
7620 # Need to explicitly forward this to override the stupid
7621 # (grid_)size method inherited from Tkinter.Toplevel.Grid.
7622 def size(self):
7623 return self.component('listbox').size()
7624
7625 # Need to explicitly forward this to override the stupid
7626 # (grid_)bbox method inherited from Tkinter.Toplevel.Grid.
7627 def bbox(self, index):
7628 return self.component('listbox').size(index)
7629
7630 forwardmethods(SelectionDialog, ScrolledListBox, '_list')
7631
7632 ######################################################################
7633 ### File: PmwTextDialog.py
7634 # A Dialog with a ScrolledText widget.
7635
7636
7637
7638 class TextDialog(Dialog):
7639 def __init__(self, parent = None, **kw):
7640 # Define the megawidget options.
7641
7642 optiondefs = (
7643 ('borderx', 10, INITOPT),
7644 ('bordery', 10, INITOPT),
7645 )
7646 self.defineoptions(kw, optiondefs)
7647
7648 # Initialise the base class (after defining the options).
7649 Dialog.__init__(self, parent)
7650
7651 # Create the components.
7652 interior = self.interior()
7653 aliases = (
7654 ('text', 'scrolledtext_text'),
7655 ('label', 'scrolledtext_label'),
7656 )
7657 self._text = self.createcomponent('scrolledtext',
7658 aliases, None,
7659 ScrolledText, (interior,))
7660 self._text.pack(side='top', expand=1, fill='both',
7661 padx = self['borderx'], pady = self['bordery'])
7662
7663 # Check keywords and initialise options.
7664 self.initialiseoptions()
7665
7666 # Need to explicitly forward this to override the stupid
7667 # (grid_)bbox method inherited from Tkinter.Toplevel.Grid.
7668 def bbox(self, index):
7669 return self._text.bbox(index)
7670
7671 forwardmethods(TextDialog, ScrolledText, '_text')
7672
7673 ######################################################################
7674 ### File: PmwTimeCounter.py
7675 # Authors: Joe VanAndel and Greg McFarlane
7676
7677 import sys
7678 import time
7679
7680
7681 class TimeCounter(MegaWidget):
7682 """Up-down counter
7683
7684 A TimeCounter is a single-line entry widget with Up and Down arrows
7685 which increment and decrement the Time value in the entry.
7686 """
7687
7688 def __init__(self, parent = None, **kw):
7689
7690 # Define the megawidget options.
7691
7692 optiondefs = (
7693 ('autorepeat', 1, None),
7694 ('buttonaspect', 1.0, INITOPT),
7695 ('command', None, None),
7696 ('initwait', 300, None),
7697 ('labelmargin', 0, INITOPT),
7698 ('labelpos', None, INITOPT),
7699 ('max', None, self._max),
7700 ('min', None, self._min),
7701 ('padx', 0, INITOPT),
7702 ('pady', 0, INITOPT),
7703 ('repeatrate', 50, None),
7704 ('value', None, INITOPT),
7705 )
7706 self.defineoptions(kw, optiondefs)
7707
7708 # Initialise the base class (after defining the options).
7709 MegaWidget.__init__(self, parent)
7710
7711 self.arrowDirection = {}
7712 self._flag = 'stopped'
7713 self._timerId = None
7714
7715 self._createComponents(kw)
7716
7717 value = self['value']
7718 if value is None:
7719 now = time.time()
7720 value = time.strftime('%H:%M:%S', time.localtime(now))
7721 self.setvalue(value)
7722
7723 # Check keywords and initialise options.
7724 self.initialiseoptions()
7725
7726 def _createComponents(self, kw):
7727
7728 # Create the components.
7729 interior = self.interior()
7730
7731 # If there is no label, put the arrows and the entry directly
7732 # into the interior, otherwise create a frame for them. In
7733 # either case the border around the arrows and the entry will
7734 # be raised (but not around the label).
7735 if self['labelpos'] is None:
7736 frame = interior
7737 if 'hull_relief' not in kw:
7738 frame.configure(relief = 'raised')
7739 if 'hull_borderwidth' not in kw:
7740 frame.configure(borderwidth = 1)
7741 else:
7742 frame = self.createcomponent('frame',
7743 (), None,
7744 Tkinter.Frame, (interior,),
7745 relief = 'raised', borderwidth = 1)
7746 frame.grid(column=2, row=2, sticky='nsew')
7747 interior.grid_columnconfigure(2, weight=1)
7748 interior.grid_rowconfigure(2, weight=1)
7749
7750 # Create the down arrow buttons.
7751
7752 # Create the hour down arrow.
7753 self._downHourArrowBtn = self.createcomponent('downhourarrow',
7754 (), 'Arrow',
7755 Tkinter.Canvas, (frame,),
7756 width = 16, height = 16, relief = 'raised', borderwidth = 2)
7757 self.arrowDirection[self._downHourArrowBtn] = 'down'
7758 self._downHourArrowBtn.grid(column = 0, row = 2)
7759
7760 # Create the minute down arrow.
7761 self._downMinuteArrowBtn = self.createcomponent('downminutearrow',
7762 (), 'Arrow',
7763 Tkinter.Canvas, (frame,),
7764 width = 16, height = 16, relief = 'raised', borderwidth = 2)
7765 self.arrowDirection[self._downMinuteArrowBtn] = 'down'
7766 self._downMinuteArrowBtn.grid(column = 1, row = 2)
7767
7768 # Create the second down arrow.
7769 self._downSecondArrowBtn = self.createcomponent('downsecondarrow',
7770 (), 'Arrow',
7771 Tkinter.Canvas, (frame,),
7772 width = 16, height = 16, relief = 'raised', borderwidth = 2)
7773 self.arrowDirection[self._downSecondArrowBtn] = 'down'
7774 self._downSecondArrowBtn.grid(column = 2, row = 2)
7775
7776 # Create the entry fields.
7777
7778 # Create the hour entry field.
7779 self._hourCounterEntry = self.createcomponent('hourentryfield',
7780 (('hourentry', 'hourentryfield_entry'),), None,
7781 EntryField, (frame,), validate='integer', entry_width = 2)
7782 self._hourCounterEntry.grid(column = 0, row = 1, sticky = 'news')
7783
7784 # Create the minute entry field.
7785 self._minuteCounterEntry = self.createcomponent('minuteentryfield',
7786 (('minuteentry', 'minuteentryfield_entry'),), None,
7787 EntryField, (frame,), validate='integer', entry_width = 2)
7788 self._minuteCounterEntry.grid(column = 1, row = 1, sticky = 'news')
7789
7790 # Create the second entry field.
7791 self._secondCounterEntry = self.createcomponent('secondentryfield',
7792 (('secondentry', 'secondentryfield_entry'),), None,
7793 EntryField, (frame,), validate='integer', entry_width = 2)
7794 self._secondCounterEntry.grid(column = 2, row = 1, sticky = 'news')
7795
7796 # Create the up arrow buttons.
7797
7798 # Create the hour up arrow.
7799 self._upHourArrowBtn = self.createcomponent('uphourarrow',
7800 (), 'Arrow',
7801 Tkinter.Canvas, (frame,),
7802 width = 16, height = 16, relief = 'raised', borderwidth = 2)
7803 self.arrowDirection[self._upHourArrowBtn] = 'up'
7804 self._upHourArrowBtn.grid(column = 0, row = 0)
7805
7806 # Create the minute up arrow.
7807 self._upMinuteArrowBtn = self.createcomponent('upminutearrow',
7808 (), 'Arrow',
7809 Tkinter.Canvas, (frame,),
7810 width = 16, height = 16, relief = 'raised', borderwidth = 2)
7811 self.arrowDirection[self._upMinuteArrowBtn] = 'up'
7812 self._upMinuteArrowBtn.grid(column = 1, row = 0)
7813
7814 # Create the second up arrow.
7815 self._upSecondArrowBtn = self.createcomponent('upsecondarrow',
7816 (), 'Arrow',
7817 Tkinter.Canvas, (frame,),
7818 width = 16, height = 16, relief = 'raised', borderwidth = 2)
7819 self.arrowDirection[self._upSecondArrowBtn] = 'up'
7820 self._upSecondArrowBtn.grid(column = 2, row = 0)
7821
7822 # Make it resize nicely.
7823 padx = self['padx']
7824 pady = self['pady']
7825 for col in range(3):
7826 frame.grid_columnconfigure(col, weight = 1, pad = padx)
7827 frame.grid_rowconfigure(0, pad = pady)
7828 frame.grid_rowconfigure(2, pad = pady)
7829
7830 frame.grid_rowconfigure(1, weight = 1)
7831
7832 # Create the label.
7833 self.createlabel(interior)
7834
7835 # Set bindings.
7836
7837 # Up hour
7838 self._upHourArrowBtn.bind('<Configure>',
7839 lambda event, s=self,button=self._upHourArrowBtn:
7840 s._drawArrow(button, 'up'))
7841
7842 self._upHourArrowBtn.bind('<1>',
7843 lambda event, s=self,button=self._upHourArrowBtn:
7844 s._countUp(button, 3600))
7845
7846 self._upHourArrowBtn.bind('<Any-ButtonRelease-1>',
7847 lambda event, s=self, button=self._upHourArrowBtn:
7848 s._stopUpDown(button))
7849
7850 # Up minute
7851 self._upMinuteArrowBtn.bind('<Configure>',
7852 lambda event, s=self,button=self._upMinuteArrowBtn:
7853 s._drawArrow(button, 'up'))
7854
7855
7856 self._upMinuteArrowBtn.bind('<1>',
7857 lambda event, s=self,button=self._upMinuteArrowBtn:
7858 s._countUp(button, 60))
7859
7860 self._upMinuteArrowBtn.bind('<Any-ButtonRelease-1>',
7861 lambda event, s=self, button=self._upMinuteArrowBtn:
7862 s._stopUpDown(button))
7863
7864 # Up second
7865 self._upSecondArrowBtn.bind('<Configure>',
7866 lambda event, s=self,button=self._upSecondArrowBtn:
7867 s._drawArrow(button, 'up'))
7868
7869
7870 self._upSecondArrowBtn.bind('<1>',
7871 lambda event, s=self,button=self._upSecondArrowBtn:
7872 s._countUp(button, 1))
7873
7874 self._upSecondArrowBtn.bind('<Any-ButtonRelease-1>',
7875 lambda event, s=self, button=self._upSecondArrowBtn:
7876 s._stopUpDown(button))
7877
7878 # Down hour
7879 self._downHourArrowBtn.bind('<Configure>',
7880 lambda event, s=self,button=self._downHourArrowBtn:
7881 s._drawArrow(button, 'down'))
7882
7883 self._downHourArrowBtn.bind('<1>',
7884 lambda event, s=self,button=self._downHourArrowBtn:
7885 s._countDown(button, 3600))
7886 self._downHourArrowBtn.bind('<Any-ButtonRelease-1>',
7887 lambda event, s=self, button=self._downHourArrowBtn:
7888 s._stopUpDown(button))
7889
7890
7891 # Down minute
7892 self._downMinuteArrowBtn.bind('<Configure>',
7893 lambda event, s=self,button=self._downMinuteArrowBtn:
7894 s._drawArrow(button, 'down'))
7895
7896 self._downMinuteArrowBtn.bind('<1>',
7897 lambda event, s=self,button=self._downMinuteArrowBtn:
7898 s._countDown(button, 60))
7899 self._downMinuteArrowBtn.bind('<Any-ButtonRelease-1>',
7900 lambda event, s=self, button=self._downMinuteArrowBtn:
7901 s._stopUpDown(button))
7902
7903 # Down second
7904 self._downSecondArrowBtn.bind('<Configure>',
7905 lambda event, s=self,button=self._downSecondArrowBtn:
7906 s._drawArrow(button, 'down'))
7907
7908 self._downSecondArrowBtn.bind('<1>',
7909 lambda event, s=self, button=self._downSecondArrowBtn:
7910 s._countDown(button,1))
7911 self._downSecondArrowBtn.bind('<Any-ButtonRelease-1>',
7912 lambda event, s=self, button=self._downSecondArrowBtn:
7913 s._stopUpDown(button))
7914
7915 self._hourCounterEntry.component('entry').bind(
7916 '<Return>', self._invoke)
7917 self._minuteCounterEntry.component('entry').bind(
7918 '<Return>', self._invoke)
7919 self._secondCounterEntry.component('entry').bind(
7920 '<Return>', self._invoke)
7921
7922 self._hourCounterEntry.bind('<Configure>', self._resizeArrow)
7923 self._minuteCounterEntry.bind('<Configure>', self._resizeArrow)
7924 self._secondCounterEntry.bind('<Configure>', self._resizeArrow)
7925
7926 def _drawArrow(self, arrow, direction):
7927 drawarrow(arrow, self['hourentry_foreground'], direction, 'arrow')
7928
7929 def _resizeArrow(self, event = None):
7930 for btn in (self._upHourArrowBtn, self._upMinuteArrowBtn,
7931 self._upSecondArrowBtn,
7932 self._downHourArrowBtn,
7933 self._downMinuteArrowBtn, self._downSecondArrowBtn):
7934 bw = (int(btn['borderwidth']) +
7935 int(btn['highlightthickness']))
7936 newHeight = self._hourCounterEntry.winfo_reqheight() - 2 * bw
7937 newWidth = int(newHeight * self['buttonaspect'])
7938 btn.configure(width=newWidth, height=newHeight)
7939 self._drawArrow(btn, self.arrowDirection[btn])
7940
7941 def _min(self):
7942 min = self['min']
7943 if min is None:
7944 self._minVal = 0
7945 else:
7946 self._minVal = timestringtoseconds(min)
7947
7948 def _max(self):
7949 max = self['max']
7950 if max is None:
7951 self._maxVal = None
7952 else:
7953 self._maxVal = timestringtoseconds(max)
7954
7955 def getvalue(self):
7956 return self.getstring()
7957
7958 def setvalue(self, text):
7959 list = text.split(':')
7960 if len(list) != 3:
7961 raise ValueError('invalid value: ' + text)
7962
7963 self._hour = int(list[0])
7964 self._minute = int(list[1])
7965 self._second = int(list[2])
7966
7967 self._setHMS()
7968
7969 def getstring(self):
7970 return '%02d:%02d:%02d' % (self._hour, self._minute, self._second)
7971
7972 def getint(self):
7973 return self._hour * 3600 + self._minute * 60 + self._second
7974
7975 def _countUp(self, button, increment):
7976 self._relief = self._upHourArrowBtn.cget('relief')
7977 button.configure(relief='sunken')
7978 self._count(1, 'start', increment)
7979
7980 def _countDown(self, button, increment):
7981
7982 self._relief = self._downHourArrowBtn.cget('relief')
7983 button.configure(relief='sunken')
7984 self._count(-1, 'start', increment)
7985
7986 def increment(self, seconds = 1):
7987 self._count(1, 'force', seconds)
7988
7989 def decrement(self, seconds = 1):
7990 self._count(-1, 'force', seconds)
7991
7992 def _count(self, factor, newFlag = None, increment = 1):
7993 if newFlag != 'force':
7994 if newFlag is not None:
7995 self._flag = newFlag
7996
7997 if self._flag == 'stopped':
7998 return
7999
8000 value = (int(self._hourCounterEntry.get()) *3600) + \
8001 (int(self._minuteCounterEntry.get()) *60) + \
8002 int(self._secondCounterEntry.get()) + \
8003 factor * increment
8004 min = self._minVal
8005 max = self._maxVal
8006 if value < min:
8007 value = min
8008 if max is not None and value > max:
8009 value = max
8010
8011 self._hour = value /3600
8012 self._minute = (value - (self._hour*3600)) / 60
8013 self._second = value - (self._hour*3600) - (self._minute*60)
8014 self._setHMS()
8015
8016 if newFlag != 'force':
8017 if self['autorepeat']:
8018 if self._flag == 'start':
8019 delay = self['initwait']
8020 self._flag = 'running'
8021 else:
8022 delay = self['repeatrate']
8023 self._timerId = self.after(
8024 delay, lambda self=self, factor=factor,increment=increment:
8025 self._count(factor,'running', increment))
8026
8027 def _setHMS(self):
8028 self._hourCounterEntry.setentry('%02d' % self._hour)
8029 self._minuteCounterEntry.setentry('%02d' % self._minute)
8030 self._secondCounterEntry.setentry('%02d' % self._second)
8031
8032 def _stopUpDown(self, button):
8033 if self._timerId is not None:
8034 self.after_cancel(self._timerId)
8035 self._timerId = None
8036 button.configure(relief=self._relief)
8037 self._flag = 'stopped'
8038
8039 def _invoke(self, event):
8040 cmd = self['command']
8041 if hasattr(cmd, '__call__'):
8042 cmd()
8043
8044 def invoke(self):
8045 cmd = self['command']
8046 if hasattr(cmd, '__call__'):
8047 return cmd()
8048
8049 def destroy(self):
8050 if self._timerId is not None:
8051 self.after_cancel(self._timerId)
8052 self._timerId = None
8053 MegaWidget.destroy(self)
8054
8055 ######################################################################
8056 ### File: PmwAboutDialog.py
8057
8058
8059 class AboutDialog(MessageDialog):
8060 # Window to display version and contact information.
8061
8062 # Class members containing resettable 'default' values:
8063 _version = ''
8064 _copyright = ''
8065 _contact = ''
8066
8067 def __init__(self, parent = None, **kw):
8068
8069 # Define the megawidget options.
8070
8071 optiondefs = (
8072 ('applicationname', '', INITOPT),
8073 ('iconpos', 'w', None),
8074 ('icon_bitmap', 'info', None),
8075 ('buttons', ('Close',), None),
8076 ('defaultbutton', 0, None),
8077 )
8078 self.defineoptions(kw, optiondefs)
8079
8080 # Initialise the base class (after defining the options).
8081 MessageDialog.__init__(self, parent)
8082
8083 applicationname = self['applicationname']
8084 if 'title' not in kw:
8085 self.configure(title = 'About ' + applicationname)
8086
8087 if 'message_text' not in kw:
8088 text = applicationname + '\n\n'
8089 if AboutDialog._version != '':
8090 text = text + 'Version ' + AboutDialog._version + '\n'
8091 if AboutDialog._copyright != '':
8092 text = text + AboutDialog._copyright + '\n\n'
8093 if AboutDialog._contact != '':
8094 text = text + AboutDialog._contact
8095
8096 self.configure(message_text=text)
8097
8098 # Check keywords and initialise options.
8099 self.initialiseoptions()
8100
8101 def aboutversion(value):
8102 AboutDialog._version = value
8103
8104 def aboutcopyright(value):
8105 AboutDialog._copyright = value
8106
8107 def aboutcontact(value):
8108 AboutDialog._contact = value
8109
8110 ######################################################################
8111 ### File: PmwComboBox.py
8112 # Based on iwidgets2.2.0/combobox.itk code.
8113
8114 import os
8115
8116
8117 class ComboBox(MegaWidget):
8118 def __init__(self, parent = None, **kw):
8119
8120 # Define the megawidget options.
8121
8122 optiondefs = (
8123 ('autoclear', 0, INITOPT),
8124 ('buttonaspect', 1.0, INITOPT),
8125 ('dropdown', 1, INITOPT),
8126 ('fliparrow', 0, INITOPT),
8127 ('history', 1, INITOPT),
8128 ('labelmargin', 0, INITOPT),
8129 ('labelpos', None, INITOPT),
8130 ('listheight', 200, INITOPT),
8131 ('selectioncommand', None, None),
8132 ('sticky', 'ew', INITOPT),
8133 ('unique', 1, INITOPT),
8134 )
8135 self.defineoptions(kw, optiondefs)
8136
8137 # Initialise the base class (after defining the options).
8138 MegaWidget.__init__(self, parent)
8139
8140 # Create the components.
8141 interior = self.interior()
8142
8143 self._entryfield = self.createcomponent('entryfield',
8144 (('entry', 'entryfield_entry'),), None,
8145 EntryField, (interior,))
8146 self._entryfield.grid(column=2, row=2, sticky=self['sticky'])
8147 interior.grid_columnconfigure(2, weight = 1)
8148 self._entryWidget = self._entryfield.component('entry')
8149
8150 if self['dropdown']:
8151 self._isPosted = 0
8152 interior.grid_rowconfigure(2, weight = 1)
8153
8154 # Create the arrow button.
8155 self._arrowBtn = self.createcomponent('arrowbutton',
8156 (), None,
8157 Tkinter.Canvas, (interior,), borderwidth = 2,
8158 relief = 'raised',
8159 width = 16, height = 16)
8160 if 'n' in self['sticky']:
8161 sticky = 'n'
8162 else:
8163 sticky = ''
8164 if 's' in self['sticky']:
8165 sticky = sticky + 's'
8166 self._arrowBtn.grid(column=3, row=2, sticky = sticky)
8167 self._arrowRelief = self._arrowBtn.cget('relief')
8168
8169 # Create the label.
8170 self.createlabel(interior, childCols=2)
8171
8172 # Create the dropdown window.
8173 self._popup = self.createcomponent('popup',
8174 (), None,
8175 Tkinter.Toplevel, (interior,))
8176 self._popup.withdraw()
8177 self._popup.overrideredirect(1)
8178
8179 # Create the scrolled listbox inside the dropdown window.
8180 self._list = self.createcomponent('scrolledlist',
8181 (('listbox', 'scrolledlist_listbox'),), None,
8182 ScrolledListBox, (self._popup,),
8183 hull_borderwidth = 2,
8184 hull_relief = 'raised',
8185 hull_height = self['listheight'],
8186 usehullsize = 1,
8187 listbox_exportselection = 0)
8188 self._list.pack(expand=1, fill='both')
8189 self.__listbox = self._list.component('listbox')
8190
8191 # Bind events to the arrow button.
8192 self._arrowBtn.bind('<1>', self._postList)
8193 self._arrowBtn.bind('<Configure>', self._drawArrow)
8194 self._arrowBtn.bind('<3>', self._next)
8195 self._arrowBtn.bind('<Shift-3>', self._previous)
8196 self._arrowBtn.bind('<Down>', self._next)
8197 self._arrowBtn.bind('<Up>', self._previous)
8198 self._arrowBtn.bind('<Control-n>', self._next)
8199 self._arrowBtn.bind('<Control-p>', self._previous)
8200 self._arrowBtn.bind('<Shift-Down>', self._postList)
8201 self._arrowBtn.bind('<Shift-Up>', self._postList)
8202 self._arrowBtn.bind('<F34>', self._postList)
8203 self._arrowBtn.bind('<F28>', self._postList)
8204 self._arrowBtn.bind('<space>', self._postList)
8205
8206 # Bind events to the dropdown window.
8207 self._popup.bind('<Escape>', self._unpostList)
8208 self._popup.bind('<space>', self._selectUnpost)
8209 self._popup.bind('<Return>', self._selectUnpost)
8210 self._popup.bind('<ButtonRelease-1>', self._dropdownBtnRelease)
8211 self._popup.bind('<ButtonPress-1>', self._unpostOnNextRelease)
8212
8213 # Bind events to the Tk listbox.
8214 self.__listbox.bind('<Enter>', self._unpostOnNextRelease)
8215
8216 # Bind events to the Tk entry widget.
8217 self._entryWidget.bind('<Configure>', self._resizeArrow)
8218 self._entryWidget.bind('<Shift-Down>', self._postList)
8219 self._entryWidget.bind('<Shift-Up>', self._postList)
8220 self._entryWidget.bind('<F34>', self._postList)
8221 self._entryWidget.bind('<F28>', self._postList)
8222
8223 # Need to unpost the popup if the entryfield is unmapped (eg:
8224 # its toplevel window is withdrawn) while the popup list is
8225 # displayed.
8226 self._entryWidget.bind('<Unmap>', self._unpostList)
8227
8228 else:
8229 # Create the scrolled listbox below the entry field.
8230 self._list = self.createcomponent('scrolledlist',
8231 (('listbox', 'scrolledlist_listbox'),), None,
8232 ScrolledListBox, (interior,),
8233 selectioncommand = self._selectCmd)
8234 self._list.grid(column=2, row=3, sticky='nsew')
8235 self.__listbox = self._list.component('listbox')
8236
8237 # The scrolled listbox should expand vertically.
8238 interior.grid_rowconfigure(3, weight = 1)
8239
8240 # Create the label.
8241 self.createlabel(interior, childRows=2)
8242
8243 self._entryWidget.bind('<Down>', self._next)
8244 self._entryWidget.bind('<Up>', self._previous)
8245 self._entryWidget.bind('<Control-n>', self._next)
8246 self._entryWidget.bind('<Control-p>', self._previous)
8247 self.__listbox.bind('<Control-n>', self._next)
8248 self.__listbox.bind('<Control-p>', self._previous)
8249
8250 if self['history']:
8251 self._entryfield.configure(command=self._addHistory)
8252
8253 # Check keywords and initialise options.
8254 self.initialiseoptions()
8255
8256 def destroy(self):
8257 self._entryfield.destroy()
8258 if self['dropdown'] and self._isPosted:
8259 popgrab(self._popup)
8260 MegaWidget.destroy(self)
8261
8262 #======================================================================
8263
8264 # Public methods
8265
8266 def get(self, first = None, last=None):
8267 if first is None:
8268 return self._entryWidget.get()
8269 else:
8270 return self._list.get(first, last)
8271
8272 def invoke(self):
8273 if self['dropdown']:
8274 self._postList()
8275 else:
8276 return self._selectCmd()
8277
8278 def selectitem(self, index, setentry=1):
8279 if isinstance(index, str):
8280 text = index
8281 items = self._list.get(0, 'end')
8282 if text in items:
8283 index = list(items).index(text)
8284 else:
8285 raise IndexError('index "%s" not found' % text)
8286 elif setentry:
8287 text = self._list.get(0, 'end')[index]
8288
8289 self._list.select_clear(0, 'end')
8290 self._list.select_set(index, index)
8291 self._list.activate(index)
8292 self.see(index)
8293 if setentry:
8294 self._entryfield.setentry(text)
8295
8296 # Need to explicitly forward this to override the stupid
8297 # (grid_)size method inherited from Tkinter.Frame.Grid.
8298 def size(self):
8299 return self._list.size()
8300
8301 # Need to explicitly forward this to override the stupid
8302 # (grid_)bbox method inherited from Tkinter.Frame.Grid.
8303 def bbox(self, index):
8304 return self._list.bbox(index)
8305
8306 def clear(self):
8307 self._entryfield.clear()
8308 self._list.clear()
8309
8310 #======================================================================
8311
8312 # Private methods for both dropdown and simple comboboxes.
8313
8314 def _addHistory(self):
8315 input = self._entryWidget.get()
8316
8317 if input != '':
8318 index = None
8319 if self['unique']:
8320 # If item is already in list, select it and return.
8321 items = self._list.get(0, 'end')
8322 if input in items:
8323 index = list(items).index(input)
8324
8325 if index is None:
8326 index = self._list.index('end')
8327 self._list.insert('end', input)
8328
8329 self.selectitem(index)
8330 if self['autoclear']:
8331 self._entryWidget.delete(0, 'end')
8332
8333 # Execute the selectioncommand on the new entry.
8334 self._selectCmd()
8335
8336 def _next(self, event):
8337 size = self.size()
8338 if size <= 1:
8339 return
8340
8341 cursels = self.curselection()
8342
8343 if len(cursels) == 0:
8344 index = 0
8345 else:
8346 index = int(cursels[0])
8347 if index == size - 1:
8348 index = 0
8349 else:
8350 index = index + 1
8351
8352 self.selectitem(index)
8353
8354 def _previous(self, event):
8355 size = self.size()
8356 if size <= 1:
8357 return
8358
8359 cursels = self.curselection()
8360
8361 if len(cursels) == 0:
8362 index = size - 1
8363 else:
8364 index = int(cursels[0])
8365 if index == 0:
8366 index = size - 1
8367 else:
8368 index = index - 1
8369
8370 self.selectitem(index)
8371
8372 def _selectCmd(self, event=None):
8373
8374 sels = self.getcurselection()
8375 if len(sels) == 0:
8376 item = None
8377 else:
8378 item = sels[0]
8379 self._entryfield.setentry(item)
8380
8381 cmd = self['selectioncommand']
8382 if hasattr(cmd, '__call__'):
8383 if event is None:
8384 # Return result of selectioncommand for invoke() method.
8385 return cmd(item)
8386 else:
8387 cmd(item)
8388
8389 #======================================================================
8390
8391 # Private methods for dropdown combobox.
8392
8393 def _drawArrow(self, event=None, sunken=0):
8394 arrow = self._arrowBtn
8395 if sunken:
8396 self._arrowRelief = arrow.cget('relief')
8397 arrow.configure(relief = 'sunken')
8398 else:
8399 arrow.configure(relief = self._arrowRelief)
8400
8401 if self._isPosted and self['fliparrow']:
8402 direction = 'up'
8403 else:
8404 direction = 'down'
8405 drawarrow(arrow, self['entry_foreground'], direction, 'arrow')
8406
8407 def _postList(self, event = None):
8408 self._isPosted = 1
8409 self._drawArrow(sunken=1)
8410
8411 # Make sure that the arrow is displayed sunken.
8412 self.update_idletasks()
8413
8414 x = self._entryfield.winfo_rootx()
8415 y = self._entryfield.winfo_rooty() + \
8416 self._entryfield.winfo_height()
8417 w = self._entryfield.winfo_width() + self._arrowBtn.winfo_width()
8418 h = self.__listbox.winfo_height()
8419 sh = self.winfo_screenheight()
8420
8421 if y + h > sh and y > sh / 2:
8422 y = self._entryfield.winfo_rooty() - h
8423
8424 self._list.configure(hull_width=w)
8425
8426 setgeometryanddeiconify(self._popup, '+%d+%d' % (x, y))
8427
8428 # Grab the popup, so that all events are delivered to it, and
8429 # set focus to the listbox, to make keyboard navigation
8430 # easier.
8431 pushgrab(self._popup, 1, self._unpostList)
8432 self.__listbox.focus_set()
8433
8434 self._drawArrow()
8435
8436 # Ignore the first release of the mouse button after posting the
8437 # dropdown list, unless the mouse enters the dropdown list.
8438 self._ignoreRelease = 1
8439
8440 def _dropdownBtnRelease(self, event):
8441 if (event.widget == self._list.component('vertscrollbar') or
8442 event.widget == self._list.component('horizscrollbar')):
8443 return
8444
8445 if self._ignoreRelease:
8446 self._unpostOnNextRelease()
8447 return
8448
8449 self._unpostList()
8450
8451 if (event.x >= 0 and event.x < self.__listbox.winfo_width() and
8452 event.y >= 0 and event.y < self.__listbox.winfo_height()):
8453 self._selectCmd()
8454
8455 def _unpostOnNextRelease(self, event = None):
8456 self._ignoreRelease = 0
8457
8458 def _resizeArrow(self, event):
8459 bw = (int(self._arrowBtn['borderwidth']) +
8460 int(self._arrowBtn['highlightthickness']))
8461 newHeight = self._entryfield.winfo_reqheight() - 2 * bw
8462 newWidth = int(newHeight * self['buttonaspect'])
8463 self._arrowBtn.configure(width=newWidth, height=newHeight)
8464 self._drawArrow()
8465
8466 def _unpostList(self, event=None):
8467 if not self._isPosted:
8468 # It is possible to get events on an unposted popup. For
8469 # example, by repeatedly pressing the space key to post
8470 # and unpost the popup. The <space> event may be
8471 # delivered to the popup window even though
8472 # popgrab() has set the focus away from the
8473 # popup window. (Bug in Tk?)
8474 return
8475
8476 # Restore the focus before withdrawing the window, since
8477 # otherwise the window manager may take the focus away so we
8478 # can't redirect it. Also, return the grab to the next active
8479 # window in the stack, if any.
8480 popgrab(self._popup)
8481 self._popup.withdraw()
8482
8483 self._isPosted = 0
8484 self._drawArrow()
8485
8486 def _selectUnpost(self, event):
8487 self._unpostList()
8488 self._selectCmd()
8489
8490 forwardmethods(ComboBox, ScrolledListBox, '_list')
8491 forwardmethods(ComboBox, EntryField, '_entryfield')
8492
8493 ######################################################################
8494 ### File: PmwComboBoxDialog.py
8495 # Not Based on iwidgets version.
8496
8497
8498
8499 class ComboBoxDialog(Dialog):
8500 # Dialog window with simple combobox.
8501
8502 # Dialog window displaying a list and entry field and requesting
8503 # the user to make a selection or enter a value
8504
8505 def __init__(self, parent = None, **kw):
8506 # Define the megawidget options.
8507
8508 optiondefs = (
8509 ('borderx', 10, INITOPT),
8510 ('bordery', 10, INITOPT),
8511 )
8512 self.defineoptions(kw, optiondefs)
8513
8514 # Initialise the base class (after defining the options).
8515 Dialog.__init__(self, parent)
8516
8517 # Create the components.
8518 interior = self.interior()
8519
8520 aliases = (
8521 ('listbox', 'combobox_listbox'),
8522 ('scrolledlist', 'combobox_scrolledlist'),
8523 ('entry', 'combobox_entry'),
8524 ('label', 'combobox_label'),
8525 )
8526 self._combobox = self.createcomponent('combobox',
8527 aliases, None,
8528 ComboBox, (interior,),
8529 scrolledlist_dblclickcommand = self.invoke,
8530 dropdown = 0,
8531 )
8532 self._combobox.pack(side='top', expand='true', fill='both',
8533 padx = self['borderx'], pady = self['bordery'])
8534
8535 if 'activatecommand' not in kw:
8536 # Whenever this dialog is activated, set the focus to the
8537 # ComboBox's listbox widget.
8538 listbox = self.component('listbox')
8539 self.configure(activatecommand = listbox.focus_set)
8540
8541 # Check keywords and initialise options.
8542 self.initialiseoptions()
8543
8544 # Need to explicitly forward this to override the stupid
8545 # (grid_)size method inherited from Tkinter.Toplevel.Grid.
8546 def size(self):
8547 return self._combobox.size()
8548
8549 # Need to explicitly forward this to override the stupid
8550 # (grid_)bbox method inherited from Tkinter.Toplevel.Grid.
8551 def bbox(self, index):
8552 return self._combobox.bbox(index)
8553
8554 forwardmethods(ComboBoxDialog, ComboBox, '_combobox')
8555
8556 ######################################################################
8557 ### File: PmwCounter.py
8558 import sys
8559
8560
8561 class Counter(MegaWidget):
8562
8563 def __init__(self, parent = None, **kw):
8564
8565 # Define the megawidget options.
8566
8567 optiondefs = (
8568 ('autorepeat', 1, None),
8569 ('buttonaspect', 1.0, INITOPT),
8570 ('datatype', 'numeric', self._datatype),
8571 ('increment', 1, None),
8572 ('initwait', 300, None),
8573 ('labelmargin', 0, INITOPT),
8574 ('labelpos', None, INITOPT),
8575 ('orient', 'horizontal', INITOPT),
8576 ('padx', 0, INITOPT),
8577 ('pady', 0, INITOPT),
8578 ('repeatrate', 50, None),
8579 ('sticky', 'ew', INITOPT),
8580 )
8581 self.defineoptions(kw, optiondefs)
8582
8583 # Initialise the base class (after defining the options).
8584 MegaWidget.__init__(self, parent)
8585
8586 # Initialise instance variables.
8587 self._timerId = None
8588 self._normalRelief = None
8589
8590 # Create the components.
8591 interior = self.interior()
8592
8593 # If there is no label, put the arrows and the entry directly
8594 # into the interior, otherwise create a frame for them. In
8595 # either case the border around the arrows and the entry will
8596 # be raised (but not around the label).
8597 if self['labelpos'] is None:
8598 frame = interior
8599 if 'hull_relief' not in kw:
8600 frame.configure(relief = 'raised')
8601 if 'hull_borderwidth' not in kw:
8602 frame.configure(borderwidth = 1)
8603 else:
8604 frame = self.createcomponent('frame',
8605 (), None,
8606 Tkinter.Frame, (interior,),
8607 relief = 'raised', borderwidth = 1)
8608 frame.grid(column=2, row=2, sticky=self['sticky'])
8609 interior.grid_columnconfigure(2, weight=1)
8610 interior.grid_rowconfigure(2, weight=1)
8611
8612 # Create the down arrow.
8613 self._downArrowBtn = self.createcomponent('downarrow',
8614 (), 'Arrow',
8615 Tkinter.Canvas, (frame,),
8616 width = 16, height = 16, relief = 'raised', borderwidth = 2)
8617
8618 # Create the entry field.
8619 self._counterEntry = self.createcomponent('entryfield',
8620 (('entry', 'entryfield_entry'),), None,
8621 EntryField, (frame,))
8622
8623 # Create the up arrow.
8624 self._upArrowBtn = self.createcomponent('uparrow',
8625 (), 'Arrow',
8626 Tkinter.Canvas, (frame,),
8627 width = 16, height = 16, relief = 'raised', borderwidth = 2)
8628
8629 padx = self['padx']
8630 pady = self['pady']
8631 orient = self['orient']
8632 if orient == 'horizontal':
8633 self._downArrowBtn.grid(column = 0, row = 0)
8634 self._counterEntry.grid(column = 1, row = 0,
8635 sticky = self['sticky'])
8636 self._upArrowBtn.grid(column = 2, row = 0)
8637 frame.grid_columnconfigure(1, weight = 1)
8638 frame.grid_rowconfigure(0, weight = 1)
8639 if Tkinter.TkVersion >= 4.2:
8640 frame.grid_columnconfigure(0, pad = padx)
8641 frame.grid_columnconfigure(2, pad = padx)
8642 frame.grid_rowconfigure(0, pad = pady)
8643 elif orient == 'vertical':
8644 self._upArrowBtn.grid(column = 0, row = 0, sticky = 's')
8645 self._counterEntry.grid(column = 0, row = 1,
8646 sticky = self['sticky'])
8647 self._downArrowBtn.grid(column = 0, row = 2, sticky = 'n')
8648 frame.grid_columnconfigure(0, weight = 1)
8649 frame.grid_rowconfigure(0, weight = 1)
8650 frame.grid_rowconfigure(2, weight = 1)
8651 if Tkinter.TkVersion >= 4.2:
8652 frame.grid_rowconfigure(0, pad = pady)
8653 frame.grid_rowconfigure(2, pad = pady)
8654 frame.grid_columnconfigure(0, pad = padx)
8655 else:
8656 raise ValueError('bad orient option ' + repr(orient) + \
8657 ': must be either \'horizontal\' or \'vertical\'')
8658
8659 self.createlabel(interior)
8660
8661 self._upArrowBtn.bind('<Configure>', self._drawUpArrow)
8662 self._upArrowBtn.bind('<1>', self._countUp)
8663 self._upArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting)
8664 self._downArrowBtn.bind('<Configure>', self._drawDownArrow)
8665 self._downArrowBtn.bind('<1>', self._countDown)
8666 self._downArrowBtn.bind('<Any-ButtonRelease-1>', self._stopCounting)
8667 self._counterEntry.bind('<Configure>', self._resizeArrow)
8668 entry = self._counterEntry.component('entry')
8669 entry.bind('<Down>', lambda event, s = self: s._key_decrement(event))
8670 entry.bind('<Up>', lambda event, s = self: s._key_increment(event))
8671
8672 # Need to cancel the timer if an arrow button is unmapped (eg:
8673 # its toplevel window is withdrawn) while the mouse button is
8674 # held down. The canvas will not get the ButtonRelease event
8675 # if it is not mapped, since the implicit grab is cancelled.
8676 self._upArrowBtn.bind('<Unmap>', self._stopCounting)
8677 self._downArrowBtn.bind('<Unmap>', self._stopCounting)
8678
8679 # Check keywords and initialise options.
8680 self.initialiseoptions()
8681
8682 def _resizeArrow(self, event):
8683 for btn in (self._upArrowBtn, self._downArrowBtn):
8684 bw = (int(btn['borderwidth']) +
8685 int(btn['highlightthickness']))
8686 newHeight = self._counterEntry.winfo_reqheight() - 2 * bw
8687 newWidth = int(newHeight * self['buttonaspect'])
8688 btn.configure(width=newWidth, height=newHeight)
8689 self._drawArrow(btn)
8690
8691 def _drawUpArrow(self, event):
8692 self._drawArrow(self._upArrowBtn)
8693
8694 def _drawDownArrow(self, event):
8695 self._drawArrow(self._downArrowBtn)
8696
8697 def _drawArrow(self, arrow):
8698 if self['orient'] == 'vertical':
8699 if arrow == self._upArrowBtn:
8700 direction = 'up'
8701 else:
8702 direction = 'down'
8703 else:
8704 if arrow == self._upArrowBtn:
8705 direction = 'right'
8706 else:
8707 direction = 'left'
8708 drawarrow(arrow, self['entry_foreground'], direction, 'arrow')
8709
8710 def _stopCounting(self, event = None):
8711 if self._timerId is not None:
8712 self.after_cancel(self._timerId)
8713 self._timerId = None
8714 if self._normalRelief is not None:
8715 button, relief = self._normalRelief
8716 button.configure(relief=relief)
8717 self._normalRelief = None
8718
8719 def _countUp(self, event):
8720 self._normalRelief = (self._upArrowBtn, self._upArrowBtn.cget('relief'))
8721 self._upArrowBtn.configure(relief='sunken')
8722 # Force arrow down (it may come up immediately, if increment fails).
8723 self._upArrowBtn.update_idletasks()
8724 self._count(1, 1)
8725
8726 def _countDown(self, event):
8727 self._normalRelief = (self._downArrowBtn, self._downArrowBtn.cget('relief'))
8728 self._downArrowBtn.configure(relief='sunken')
8729 # Force arrow down (it may come up immediately, if increment fails).
8730 self._downArrowBtn.update_idletasks()
8731 self._count(-1, 1)
8732
8733 def increment(self):
8734 self._forceCount(1)
8735
8736 def decrement(self):
8737 self._forceCount(-1)
8738
8739 def _key_increment(self, event):
8740 self._forceCount(1)
8741 self.update_idletasks()
8742
8743 def _key_decrement(self, event):
8744 self._forceCount(-1)
8745 self.update_idletasks()
8746
8747 def _datatype(self):
8748 datatype = self['datatype']
8749
8750 if isinstance(datatype, dict):
8751 self._counterArgs = datatype.copy()
8752 if 'counter' in self._counterArgs:
8753 datatype = self._counterArgs['counter']
8754 del self._counterArgs['counter']
8755 else:
8756 datatype = 'numeric'
8757 else:
8758 self._counterArgs = {}
8759
8760 if datatype in _counterCommands:
8761 self._counterCommand = _counterCommands[datatype]
8762 elif hasattr(datatype, '__call__'):
8763 self._counterCommand = datatype
8764 else:
8765 validValues = list(_counterCommands)
8766 validValues.sort()
8767 raise ValueError(('bad datatype value "%s": must be a' +
8768 ' function or one of %s') % (datatype, validValues))
8769
8770 def _forceCount(self, factor):
8771 if not self.valid():
8772 self.bell()
8773 return
8774
8775 text = self._counterEntry.get()
8776 try:
8777 value = self._counterCommand(
8778 text, factor, self['increment'], **self._counterArgs)
8779 except ValueError:
8780 self.bell()
8781 return
8782
8783 previousICursor = self._counterEntry.index('insert')
8784 if self._counterEntry.setentry(value) == OK:
8785 self._counterEntry.xview('end')
8786 self._counterEntry.icursor(previousICursor)
8787
8788 def _count(self, factor, first):
8789 if not self.valid():
8790 self.bell()
8791 return
8792
8793 self._timerId = None
8794 origtext = self._counterEntry.get()
8795 try:
8796 value = self._counterCommand(
8797 origtext, factor, self['increment'], **self._counterArgs)
8798 except ValueError:
8799 # If text is invalid, stop counting.
8800 self._stopCounting()
8801 self.bell()
8802 return
8803
8804 # If incrementing produces an invalid value, restore previous
8805 # text and stop counting.
8806 previousICursor = self._counterEntry.index('insert')
8807 valid = self._counterEntry.setentry(value)
8808 if valid != OK:
8809 self._stopCounting()
8810 self._counterEntry.setentry(origtext)
8811 if valid == PARTIAL:
8812 self.bell()
8813 return
8814 self._counterEntry.xview('end')
8815 self._counterEntry.icursor(previousICursor)
8816
8817 if self['autorepeat']:
8818 if first:
8819 delay = self['initwait']
8820 else:
8821 delay = self['repeatrate']
8822 self._timerId = self.after(delay,
8823 lambda self=self, factor=factor: self._count(factor, 0))
8824
8825 def destroy(self):
8826 self._stopCounting()
8827 MegaWidget.destroy(self)
8828
8829 forwardmethods(Counter, EntryField, '_counterEntry')
8830
8831 def _changeNumber(text, factor, increment):
8832 value = long(text)
8833 if factor > 0:
8834 value = (value / increment) * increment + increment
8835 else:
8836 value = ((value - 1) / increment) * increment
8837
8838 # Get rid of the 'L' at the end of longs (in python up to 1.5.2).
8839 rtn = str(value)
8840 if rtn[-1] == 'L':
8841 return rtn[:-1]
8842 else:
8843 return rtn
8844
8845 def _changeReal(text, factor, increment, separator = '.'):
8846 value = stringtoreal(text, separator)
8847 div = value / increment
8848
8849 # Compare reals using str() to avoid problems caused by binary
8850 # numbers being only approximations to decimal numbers.
8851 # For example, if value is -0.3 and increment is 0.1, then
8852 # int(value/increment) = -2, not -3 as one would expect.
8853 if str(div)[-2:] == '.0':
8854 # value is an even multiple of increment.
8855 div = round(div) + factor
8856 else:
8857 # value is not an even multiple of increment.
8858 div = int(div) * 1.0
8859 if value < 0:
8860 div = div - 1
8861 if factor > 0:
8862 div = (div + 1)
8863
8864 value = div * increment
8865
8866 text = str(value)
8867 if separator != '.':
8868 index = text.find('.')
8869 if index >= 0:
8870 text = text[:index] + separator + text[index + 1:]
8871 return text
8872
8873 def _changeDate(value, factor, increment, format = 'ymd',
8874 separator = '/', yyyy = 0):
8875
8876 jdn = datestringtojdn(value, format, separator) + factor * increment
8877
8878 y, m, d = jdntoymd(jdn)
8879 result = ''
8880 for index in range(3):
8881 if index > 0:
8882 result = result + separator
8883 f = format[index]
8884 if f == 'y':
8885 if yyyy:
8886 result = result + '%02d' % y
8887 else:
8888 result = result + '%02d' % (y % 100)
8889 elif f == 'm':
8890 result = result + '%02d' % m
8891 elif f == 'd':
8892 result = result + '%02d' % d
8893
8894 return result
8895
8896 _SECSPERDAY = 24 * 60 * 60
8897 def _changeTime(value, factor, increment, separator = ':', time24 = 0):
8898 unixTime = timestringtoseconds(value, separator)
8899 if factor > 0:
8900 chunks = unixTime / increment + 1
8901 else:
8902 chunks = (unixTime - 1) / increment
8903 unixTime = chunks * increment
8904 if time24:
8905 while unixTime < 0:
8906 unixTime = unixTime + _SECSPERDAY
8907 while unixTime >= _SECSPERDAY:
8908 unixTime = unixTime - _SECSPERDAY
8909 if unixTime < 0:
8910 unixTime = -unixTime
8911 sign = '-'
8912 else:
8913 sign = ''
8914 secs = unixTime % 60
8915 unixTime = unixTime / 60
8916 mins = unixTime % 60
8917 hours = unixTime / 60
8918 return '%s%02d%s%02d%s%02d' % (sign, hours, separator, mins, separator, secs)
8919
8920 # hexadecimal, alphabetic, alphanumeric not implemented
8921 _counterCommands = {
8922 'numeric' : _changeNumber, # } integer
8923 'integer' : _changeNumber, # } these two use the same function
8924 'real' : _changeReal, # real number
8925 'time' : _changeTime,
8926 'date' : _changeDate,
8927 }
8928
8929 ######################################################################
8930 ### File: PmwCounterDialog.py
8931
8932
8933 # A Dialog with a counter
8934
8935 class CounterDialog(Dialog):
8936
8937 def __init__(self, parent = None, **kw):
8938
8939 # Define the megawidget options.
8940
8941 optiondefs = (
8942 ('borderx', 20, INITOPT),
8943 ('bordery', 20, INITOPT),
8944 )
8945 self.defineoptions(kw, optiondefs)
8946
8947 # Initialise the base class (after defining the options).
8948 Dialog.__init__(self, parent)
8949
8950 # Create the components.
8951 interior = self.interior()
8952
8953 # Create the counter.
8954 aliases = (
8955 ('entryfield', 'counter_entryfield'),
8956 ('entry', 'counter_entryfield_entry'),
8957 ('label', 'counter_label')
8958 )
8959 self._cdCounter = self.createcomponent('counter',
8960 aliases, None,
8961 Counter, (interior,))
8962 self._cdCounter.pack(fill='x', expand=1,
8963 padx = self['borderx'], pady = self['bordery'])
8964
8965 if 'activatecommand' not in kw:
8966 # Whenever this dialog is activated, set the focus to the
8967 # Counter's entry widget.
8968 tkentry = self.component('entry')
8969 self.configure(activatecommand = tkentry.focus_set)
8970
8971 # Check keywords and initialise options.
8972 self.initialiseoptions()
8973
8974 # Supply aliases to some of the entry component methods.
8975 def insertentry(self, index, text):
8976 self._cdCounter.insert(index, text)
8977
8978 def deleteentry(self, first, last=None):
8979 self._cdCounter.delete(first, last)
8980
8981 def indexentry(self, index):
8982 return self._cdCounter.index(index)
8983
8984 forwardmethods(CounterDialog, Counter, '_cdCounter')
8985
8986 ######################################################################
8987 ### File: PmwLogicalFont.py
8988 import os
8989
8990 def _font_initialise(root, size=None, fontScheme = None):
8991 global _fontSize
8992 if size is not None:
8993 _fontSize = size
8994
8995 if fontScheme in ('pmw1', 'pmw2'):
8996 if os.name == 'posix':
8997 defaultFont = logicalfont('Helvetica')
8998 menuFont = logicalfont('Helvetica', weight='bold', slant='italic')
8999 scaleFont = logicalfont('Helvetica', slant='italic')
9000 root.option_add('*Font', defaultFont, 'userDefault')
9001 root.option_add('*Menu*Font', menuFont, 'userDefault')
9002 root.option_add('*Menubutton*Font', menuFont, 'userDefault')
9003 root.option_add('*Scale.*Font', scaleFont, 'userDefault')
9004
9005 if fontScheme == 'pmw1':
9006 balloonFont = logicalfont('Helvetica', -6, pixel = '12')
9007 else: # fontScheme == 'pmw2'
9008 balloonFont = logicalfont('Helvetica', -2)
9009 root.option_add('*Balloon.*Font', balloonFont, 'userDefault')
9010 else:
9011 defaultFont = logicalfont('Helvetica')
9012 root.option_add('*Font', defaultFont, 'userDefault')
9013 elif fontScheme == 'default':
9014 defaultFont = ('Helvetica', '-%d' % (_fontSize,), 'bold')
9015 entryFont = ('Helvetica', '-%d' % (_fontSize,))
9016 textFont = ('Courier', '-%d' % (_fontSize,))
9017 root.option_add('*Font', defaultFont, 'userDefault')
9018 root.option_add('*Entry*Font', entryFont, 'userDefault')
9019 root.option_add('*Text*Font', textFont, 'userDefault')
9020
9021 def logicalfont(name='Helvetica', sizeIncr = 0, **kw):
9022 if name not in _fontInfo:
9023 raise ValueError('font %s does not exist' % name)
9024
9025 rtn = []
9026 for field in _fontFields:
9027 if field in kw:
9028 logicalValue = kw[field]
9029 elif field in _fontInfo[name]:
9030 logicalValue = _fontInfo[name][field]
9031 else:
9032 logicalValue = '*'
9033
9034 if (field, logicalValue) in _propertyAliases[name]:
9035 realValue = _propertyAliases[name][(field, logicalValue)]
9036 elif (field, None) in _propertyAliases[name]:
9037 realValue = _propertyAliases[name][(field, None)]
9038 elif (field, logicalValue) in _propertyAliases[None]:
9039 realValue = _propertyAliases[None][(field, logicalValue)]
9040 elif (field, None) in _propertyAliases[None]:
9041 realValue = _propertyAliases[None][(field, None)]
9042 else:
9043 realValue = logicalValue
9044
9045 if field == 'size':
9046 if realValue == '*':
9047 realValue = _fontSize
9048 realValue = str((realValue + sizeIncr) * 10)
9049
9050 rtn.append(realValue)
9051
9052 return '-'.join(rtn)
9053
9054 def logicalfontnames():
9055 return _fontInfo.keys()
9056
9057 if os.name == 'nt':
9058 _fontSize = 16
9059 else:
9060 _fontSize = 14
9061
9062 _fontFields = (
9063 'registry', 'foundry', 'family', 'weight', 'slant', 'width', 'style',
9064 'pixel', 'size', 'xres', 'yres', 'spacing', 'avgwidth', 'charset', 'encoding')
9065
9066 # <_propertyAliases> defines other names for which property values may
9067 # be known by. This is required because italics in adobe-helvetica
9068 # are specified by 'o', while other fonts use 'i'.
9069
9070 _propertyAliases = {}
9071
9072 _propertyAliases[None] = {
9073 ('slant', 'italic') : 'i',
9074 ('slant', 'normal') : 'r',
9075 ('weight', 'light') : 'normal',
9076 ('width', 'wide') : 'normal',
9077 ('width', 'condensed') : 'normal',
9078 }
9079
9080 # <_fontInfo> describes a 'logical' font, giving the default values of
9081 # some of its properties.
9082
9083 _fontInfo = {}
9084
9085 _fontInfo['Helvetica'] = {
9086 'foundry' : 'adobe',
9087 'family' : 'helvetica',
9088 'registry' : '',
9089 'charset' : 'iso8859',
9090 'encoding' : '1',
9091 'spacing' : 'p',
9092 'slant' : 'normal',
9093 'width' : 'normal',
9094 'weight' : 'normal',
9095 }
9096
9097 _propertyAliases['Helvetica'] = {
9098 ('slant', 'italic') : 'o',
9099 ('weight', 'normal') : 'medium',
9100 ('weight', 'light') : 'medium',
9101 }
9102
9103 _fontInfo['Times'] = {
9104 'foundry' : 'adobe',
9105 'family' : 'times',
9106 'registry' : '',
9107 'charset' : 'iso8859',
9108 'encoding' : '1',
9109 'spacing' : 'p',
9110 'slant' : 'normal',
9111 'width' : 'normal',
9112 'weight' : 'normal',
9113 }
9114
9115 _propertyAliases['Times'] = {
9116 ('weight', 'normal') : 'medium',
9117 ('weight', 'light') : 'medium',
9118 }
9119
9120 _fontInfo['Fixed'] = {
9121 'foundry' : 'misc',
9122 'family' : 'fixed',
9123 'registry' : '',
9124 'charset' : 'iso8859',
9125 'encoding' : '1',
9126 'spacing' : 'c',
9127 'slant' : 'normal',
9128 'width' : 'normal',
9129 'weight' : 'normal',
9130 }
9131
9132 _propertyAliases['Fixed'] = {
9133 ('weight', 'normal') : 'medium',
9134 ('weight', 'light') : 'medium',
9135 ('style', None) : '',
9136 ('width', 'condensed') : 'semicondensed',
9137 }
9138
9139 _fontInfo['Courier'] = {
9140 'foundry' : 'adobe',
9141 'family' : 'courier',
9142 'registry' : '',
9143 'charset' : 'iso8859',
9144 'encoding' : '1',
9145 'spacing' : 'm',
9146 'slant' : 'normal',
9147 'width' : 'normal',
9148 'weight' : 'normal',
9149 }
9150
9151 _propertyAliases['Courier'] = {
9152 ('weight', 'normal') : 'medium',
9153 ('weight', 'light') : 'medium',
9154 ('style', None) : '',
9155 }
9156
9157 _fontInfo['Typewriter'] = {
9158 'foundry' : 'b&h',
9159 'family' : 'lucidatypewriter',
9160 'registry' : '',
9161 'charset' : 'iso8859',
9162 'encoding' : '1',
9163 'spacing' : 'm',
9164 'slant' : 'normal',
9165 'width' : 'normal',
9166 'weight' : 'normal',
9167 }
9168
9169 _propertyAliases['Typewriter'] = {
9170 ('weight', 'normal') : 'medium',
9171 ('weight', 'light') : 'medium',
9172 }
9173
9174 if os.name == 'nt':
9175 # For some reason 'fixed' fonts on NT aren't.
9176 _fontInfo['Fixed'] = _fontInfo['Courier']
9177 _propertyAliases['Fixed'] = _propertyAliases['Courier']