tk_itemmenu.py 2.28 KB
Newer Older
1 2 3 4
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
"""
5 6 7 8
    Implements all items from menu inheriting from abstract class ItemMenu.
    
    Name: main.py
    Author: Alessandro dos Santos Ferreira ( santosferreira.alessandro@gmail.com )
9
"""
10 11 12 13 14
import sys
if sys.version_info[0] < 3:
    import Tkinter as Tk
else:
    import tkinter as Tk
15 16 17 18 19 20

from abc import ABCMeta, abstractmethod

class ItemMenu(object):
    
    __metaclass__ = ABCMeta
21 22 23 24 25 26 27
    
    parent = None
    shortcut = None
    action = None
    
    def __init__(self, parent):
        self.parent = parent
28 29 30 31 32 33 34 35 36 37

    @abstractmethod
    def render(self, menu):
        pass


class Command(ItemMenu):
    
    label = None
    
38 39
    def __init__(self, parent, label, action, shortcut = None):
        super(self.__class__, self).__init__(parent)
40 41 42 43 44 45 46 47 48 49 50 51 52 53
        self.label = label
        self.action = action
        if shortcut is not None:
            self.shortcut = str(shortcut).upper()
        
    def render(self, menu):
        accelerator = None if self.shortcut is None else "Ctrl+" + str(self.shortcut)
        underline = None if self.shortcut is None else self.label.upper().find( self.shortcut )
        
        menu.add_command(label=self.label, command=self.action, accelerator=accelerator, underline=underline)


class Separator(ItemMenu):
    
54 55
    def __init__(self, parent):
        super(self.__class__, self).__init__(parent)
56 57 58

    def render(self, menu):
        menu.add_separator()
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

        
class CheckButton(ItemMenu):
    
    label = None
    default_state = None
    
    def __init__(self, parent, label, action, shortcut = None, default_state = True):
        super(self.__class__, self).__init__(parent)
        self.label = label
        self.action = action
        if shortcut is not None:
            self.shortcut = str(shortcut).upper()
        self.default_state = default_state
        
    def render(self, menu):
        accelerator = None if self.shortcut is None else "Ctrl+" + str(self.shortcut)
        underline = None if self.shortcut is None else self.label.upper().find( self.shortcut )
        
        self.state = Tk.BooleanVar()
        self.state.set(self.default_state)
        
        menu.add_checkbutton(label=self.label, onvalue=True, offvalue=False, command=self.action, accelerator=accelerator, underline=underline, variable = self.state)