Fonts & Tinker

Paul aquagnu at gmail.com
Sat Jan 26 06:18:01 CET 2013


class FontSpec:
    """Wrapper for something like 'Arial 10 bold #red'
    """

    tkf = None # Tk Font
    spec = "" # specification
    tkspec = "" # specification for Tk
    family = None
    size = 0
    color = "black"
    weight = "normal"
    slant = "roman"
    underline = 0
    overstrike = 0
    linespace = 0
    descent = 0
    ascent = 0

    def __init__(self, spec=None):
        """spec: familty with capital letter, color with # (#red, ##FF00FF),
        size - int, other are styles"""
        try:
            if not spec:
                return

            spec = spec.split()

            family = [s for s in spec if s.istitle()]
            if family:
                self.family = family[0]
                spec.remove(self.family)

            color = [s for s in spec if s.startswith('#')]
            if color:
                self.color = color[0]
                spec.remove(self.color)
                self.color = self.color[1:]

            size = [s for s in spec if s.isdigit()]
            if size:
                self.size = size[0]
                spec.remove(self.size)
                self.size = int(self.size)

            if "bold" in spec:
                self.weight = "bold"

            if "italic" in spec:
                self.slant = "italic"

            if "underline" in spec:
                self.underline = 1

            if "overstrike" in spec:
                self.overstrike = 1

            # create tkFont for metrics
            self.tkf = tkFont.Font(family=self.family, size=self.size, weight=self.weight,
                    slant=self.slant, underline=self.underline, overstrike=self.overstrike)

            self.ascent = self.tkf.metrics("ascent")

            self.descent = self.tkf.metrics("descent")

            self.linespace = self.tkf.metrics("linespace")

            # tkspec - specific. of font in Tk standard
            self.tkspec = []
            if self.family:
                self.tkspec.append(self.family)
            if self.size:
                self.tkspec.append(str(self.size))
            if self.weight == "bold":
                self.tkspec.append("bold")
            if self.slant == "italic":
                self.tkspec.append("italic")
            if self.underline:
                self.tkspec.append("underline")
            if self.overstrike:
                self.tkspec.append("overstrike")
            self.tkspec = " ".join(self.tkspec)

        except:
            raise ValueError("invalid font specification")

    def __str__(self):
        return self.tkspec

--- only for ideas



More information about the Python-list mailing list