some additions for the tutorial

34 views
Skip to first unread message

Mathis C

unread,
Feb 24, 2017, 5:32:34 AM2/24/17
to Tk Documentation and Resources
Hi, I'm currently reading your tutorial on tk (which is awesome) and I have a few things to add if it can help :

On the page http://www.tkdocs.com/tutorial/menus.html we can get the windowing system in Python with
root._windowingsystem
In fact it can be used on any widget and that works.

The themed spinbox can also be used be the class doesn't exist in the framework so I wrote it based on the other ttk classes :
class Spinbox(ttk.Widget, tkinter.Spinbox):
   
"""Spinbox widget, themed !"""
   
def __init__(self, master=None, **kw):
        ttk
.Widget.__init__(self, master, 'ttk::spinbox', kw)

   
def configure(self, cnf=None, **kw):
       
if cnf:
            kw
.update(cnf)
        ttk
.Widget.configure(self, **kw)
       
if any(['from' in kw, 'from_' in kw, 'to' in kw]):
           
self.event_generate('<<RangeChanged>>')

And finally to get things like %d %i etc (tcl substitutions) in Python programs, we have to use a tuple with a registered command and substitions that we want, and the command will be called with the substitions as arguments in the order, ex :
cmd = widget.register(real_command)
cmd
= (cmd, '%d', '%i', '%P', '%s', '%S', '%v', '%V') # add tk params
widget
['validatecommand'] = cmd

Real example : I made an Entry subclass to facilitate validation :
ACTION_CODES = {'-1': 'other', '0': 'delete', '1': 'insert'}
vcmd_event
= namedtuple('ValidateCommandEvent',
   
'action index text_after text_before text_change validate reason')

class Entry(ttk.Entry):
   
"""Helper for ttk.Entry, particularly to validate commands"""

   
def __init__(self, master=None, validate='none', validatecommand=None, **kw):
       
# get the validate command
       
self._vcmd = validatecommand
       
# defaults validate on key if vcmd set
       
if self._vcmd is not None and validate == 'none':
            validate
= 'key'

       
super().__init__(master, validate=validate, **kw)

        cmd
= self.register(self._vcmd_impl)
        cmd
= (cmd, '%d', '%i', '%P', '%s', '%S', '%v', '%V') # add tk params
       
self['validatecommand'] = cmd

   
def _vcmd_impl(self, action, index, t_after, t_before, t_change, validate, reason):
        ret
= self._vcmd(self, vcmd_event(
            ACTION_CODES
[action],
           
int(index), # beginning of insertion/deletion
            t_after
, t_before, t_change, validate, reason,
       
))
       
assert ret in (True, False), 'The return value of the validation callback must be True or False\nThe validation on %s has been disabled, set validate to none|key|focus|focusin|focusout|all to re-enable it.' % self
       
return ret


Reply all
Reply to author
Forward
0 new messages