Skip to content

Commit

Permalink
Some improvements around cget/configure (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
rdbende authored Sep 26, 2024
1 parent 777cfbb commit fdc6e79
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions tksvg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import tkinter as tk
import os


def load(window: tk.Tk):
"""Load tksvg into a Tk interpreter"""
local = os.path.abspath(os.path.dirname(__file__))
Expand All @@ -26,39 +27,50 @@ class SvgImage(tk.PhotoImage):
This implementation is inspired by GitHub @j4321:
<https://stackoverflow.com/a/64829808>
"""
_svg_options = [("scale", float), ("scaletowidth", int), ("scaletoheight", int)]
__svg_options = {"scale": float, "scaletowidth": int, "scaletoheight": int}

def __init__(self, name=None, cnf={}, master=None, **kwargs):
self._svg_options_current = dict()
# Load TkSVG package if not yet loaded
master = master or tk._default_root
if master is None:
raise tk.TclError("No Tk instance available to get interpreter from")
if not getattr(master, "_tksvg_loaded", False):
load(master)

# Pop SvgImage keyword arguments
svg_options = {key: t(kwargs.pop(key)) for (key, t) in self._svg_options if key in kwargs}
# Initialize as a PhotoImage
svg_options = {key: kwargs.pop(key) for key in self.__svg_options if key in kwargs}

tk.PhotoImage.__init__(self, name, cnf, master, **kwargs)
self.configure(**svg_options)

def configure(self, **kwargs):
"""Configure the image with SVG options and pass to PhotoImage.configure"""
svg_options = {key: t(kwargs.pop(key)) for (key, t) in self._svg_options if key in kwargs}
if kwargs: # len(kwargs) > 0
svg_options = {key: kwargs.pop(key) for key in self.__svg_options if key in kwargs}
if kwargs:
tk.PhotoImage.configure(self, **kwargs)
options = tuple()

options = ""
for key, value in svg_options.items():
if value is not None:
options += ("-"+key, str(value))
self.tk.eval("%s configure -format {svg %s}" % (self.name, " ".join(options)))
self._svg_options_current.update(svg_options)
options += f"-{key} {value}"

self.tk.eval("%s configure -format {svg %s}" % (self.name, options))

config = configure

def cget(self, option):
"""Return the option set for an SVG property or pass to PhotoImage.cget"""
if option in (k for k, _ in self._svg_options):
return self._svg_options_current.get(option, None)
return tk.PhotoImage.cget(self, option)
if option not in self.__svg_options:
return tk.PhotoImage.cget(self, option)

type = self.__svg_options[option]
format_list = tk.PhotoImage.cget(self, "format")

for index, item in enumerate(format_list):
if str(item)[1:] == option:
return type(format_list[index+1])

return None

def __getitem__(self, key):
return self.cget(key)
Expand Down

0 comments on commit fdc6e79

Please sign in to comment.