根据系统配置(显示分辨率),所有 tk 小部件都会自动缩放,但是在按钮/标签小部件中实现的图标呢?
为了说明这一点,我写了一个带有标签和按钮的小例子:
import tkinter as tk
import io
import tksvg
from lxml import etree
import ctypes
from sys import platform
# resolution fix:
if platform == "win32":
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # windows >= 8.1
except:
ctypes.windll.user32.SetProcessDPIAware() # windows <= 8.0
# my free svg icon:
dic_tool_bar={"start":'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Pro 6.3.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><path d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z"/></svg>'}
# function to use svg icon in Tkinter:
def svg_to_image(source, fill=None, scale_to_width=None, scale_to_height=None, scale=1):
# parse xml data
root = etree.fromstring(source)
tree = etree.ElementTree(root)
# set path fill color if provided
if fill is not None:
root.attrib["fill"] = fill
imgdata = io.BytesIO()
tree.write(imgdata)
kw = {"data": imgdata.getvalue()}
if scale_to_width:
kw["scaletowidth"] = scale_to_width
if scale_to_height:
kw["scaletoheight"] = scale_to_height
if scale != 1:
kw["scale"] = scale
return tksvg.SvgImage(**kw)
class MainWindow:
def __init__(self):
self.parent=tk.Tk()
self.parent.title("TEST")
self.parent.minsize(350, 300)
self.icon_color="#484848"
self.default_font=("Segoe UI",9, "bold")
self.obj_tool_bar=ToolBar(self)
self.obj_tool_bar.pack(fill=tk.BOTH)
self.parent.mainloop()
class ToolBar(tk.Frame):
def __init__(self, mw):
super().__init__(mw.parent)
self["background"]="white"
self.default_font=mw.default_font
self.icon_color=mw.icon_color
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.name=tk.Label(self, anchor="w", background="white", text="TEST!!", font=(self.default_font))
self.border_up=tk.Frame(self, background="#bfbfbf", highlightthickness=0)
self.border_down=tk.Frame(self, background="#bfbfbf", highlightthickness=0)
self.start_logo=svg_to_image(dic_tool_bar["start"], fill=self.icon_color, scale=0.035)
self.start=tk.Button(self, relief="flat", borderwidth=0, background="white", activebackground="white", image=self.start_logo)
self.border_up.grid(column=0, row=0, sticky="new")
self.name.grid(column=0, row=1, sticky="nsw", padx=(4,4), pady=(2,2))
self.start.grid(column=0, row=1, sticky="ens", ipadx=4)
self.border_down.grid(column=0, row=2, sticky="sew")
# start
app=MainWindow()
当我更改显示设置时,标签小部件会自动缩放,但图标
self.start_logo
没有。看图:
当我必须在其他具有不同分辨率的计算机上运行代码时,这是一个大问题。我该如何解决?我怎样才能像 Tkinter 已经为标签做的那样自动缩放图标?
注意:
函数
svg_to_image
是israel-dryer编写的名为tkfontawesome
的库的一部分,您可以在Github上找到所有代码。它很简单但非常有用,从我的角度来看,它使得在 Tkinter 中使用 SVG 图标变得如此容易。你呢?你在想什么?这是一个好的代码吗?当我们必须在 Tkinter 中使用图标时,最佳做法是什么?请记住,我使用的所有图标都是 SVG 类型。