@@ -24,3 +24,57 @@ def load(window: tk.Tk):
2424 with chdir (local ):
2525 window .tk .eval ("source pkgIndex.tcl" )
2626 window .tk .eval ("package require tksvg" )
27+ window ._tksvg_loaded = True
28+
29+
30+ class SvgImage (tk .PhotoImage ):
31+ """
32+ Sub-class of tk.PhotoImage with support for SVG image options
33+
34+ tksvg provides some options to control the rastering of SVG images.
35+ These are accessible when the images is created with this class.
36+
37+ This implementation is inspired by GitHub @j4321:
38+ <https://stackoverflow.com/a/64829808>
39+ """
40+ _tksvg_loaded = False
41+ _svg_options = [("scale" , float ), ("scaletowidth" , int ), ("scaletoheight" , int )]
42+
43+ def __init__ (self , name = None , cnf = {}, master = None , ** kwargs ):
44+ self ._svg_options_current = dict ()
45+ # Load TkSVG package if not yet loaded
46+ master = master or tk ._default_root
47+ if master is None :
48+ raise tk .TclError ("No Tk instance available to get interpreter from" )
49+ if not getattr (master , "_tksvg_loaded" , False ) and not self ._tksvg_loaded :
50+ load (master )
51+ self ._tksvg_loaded = True
52+ # Pop SvgImage keyword arguments
53+ svg_options = {key : t (kwargs .pop (key )) for (key , t ) in self ._svg_options if key in kwargs }
54+ # Initialize as a PhotoImage
55+ tk .PhotoImage .__init__ (self , name , cnf , master , ** kwargs )
56+ self .configure (** svg_options )
57+
58+ def configure (self , ** kwargs ):
59+ """Configure the image with SVG options and pass to PhotoImage.configure"""
60+ svg_options = {key : t (kwargs .pop (key )) for (key , t ) in self ._svg_options if key in kwargs }
61+ if kwargs : # len(kwargs) > 0
62+ tk .PhotoImage .configure (self , ** kwargs )
63+ options = tuple ()
64+ for key , value in svg_options .items ():
65+ if value is not None :
66+ options += ("-" + key , str (value ))
67+ self .tk .eval ("%s configure -format {svg %s}" % (self .name , " " .join (options )))
68+ self ._svg_options_current .update (svg_options )
69+
70+ def cget (self , option ):
71+ """Return the option set for an SVG property or pass to PhotoImage.cget"""
72+ if option in (k for k , _ in self ._svg_options ):
73+ return self ._svg_options_current .get (option , None )
74+ return tk .PhotoImage .cget (self , option )
75+
76+ def __getitem__ (self , key ):
77+ return self .cget (key )
78+
79+ def __setitem__ (self , key , value ):
80+ return self .configure (** {key : value })
0 commit comments