感谢this question,我发现了tksvg.
我已经知道如何显示SVG文件:
import tkinter as tk
import tksvg
window = tk.Tk()
svg_image = tksvg.SvgImage(file="tests/orb.svg")
label = tk.Label(image=svg_image)
label.pack()
window.mainloop()
以及如何使用SVG数据/字符串执行相同的操作:
import tkinter as tk
import tksvg
svg_string = """
<svg aria-hidden="true" focusable="false" role="img" viewBox="0 0 24 24" class="" fill="none" stroke-width="2" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.5px" stroke="#B8B8B8" fill="none"><path stroke="none" d="M0 0h24v24H0z" fill="none" stroke-width="1.5px"></path><line x1="4" y1="20" x2="7" y2="20" stroke="#B8B8B8" fill="none" stroke-width="1.5px"></line><line x1="14" y1="20" x2="21" y2="20" stroke="#B8B8B8" fill="none" stroke-width="1.5px"></line><line x1="6.9" y1="15" x2="13.8" y2="15" stroke="#B8B8B8" fill="none" stroke-width="1.5px"></line><line x1="10.2" y1="6.3" x2="16" y2="20" stroke="#B8B8B8" fill="none" stroke-width="1.5px"></line><polyline points="5 20 11 4 13 4 20 20" stroke="#B8B8B8" fill="none" stroke-width="1.5px"></polyline></g></svg>
"""
window = tk.Tk()
svg_image = tksvg.SvgImage(data=svg_string)
label = tk.Label(image=svg_image)
label.pack()
window.mainloop()
但我想知道,如何修改SVG元素的Fill选项(基于SVG数据).
我想到的唯一方法就是重画/删除并使用Fill中使用的不同 colored颜色 创建SVG元素. 以下是我的try :
import tkinter as tk
import tksvg
svg_string = '<svg viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="red"/></svg>'
def change_color(event):
global svg_string
fill_color = "blue" if "red" in svg_string else "red"
svg_string = '<svg viewBox="0 0 100 100"><circle cx="50" cy="50" r="40" fill="{}"/></svg>'.format(fill_color)
canvas.delete(image_store[0])
svg_store.pop(0)
svg_store.append(tksvg.SvgImage(data=svg_string))
image_store[0] = canvas.create_image(100, 100, image=svg_store[0])
window = tk.Tk()
canvas = tk.Canvas(window, width=200, height=200)
canvas.pack()
image_store = []
svg_store = []
svg_store.append(tksvg.SvgImage(data=svg_string))
image_store.append(canvas.create_image(100, 100, image=svg_store[0]))
canvas.tag_bind(image_store[0], "<Button-1>", change_color)
window.mainloop()
这里我试着来回切换 colored颜色 ,这样当它是蓝色的时候,它就变成了红色,当它是红色的时候,它变成了蓝色.但在这种情况下, colored颜色 似乎只会改变一次.
我只是想做一个解决办法,因为我认为这还不受支持(如果我错了,请随时纠正我,因为我试图查看代码,尽我最大的努力理解它).
我怎么能这样做呢?是使用上述解决办法(重画元素)还是使用更好的替代方案?
我使用的是Windows 10,Python版本3.8.10,Tkinter 8.6.9