如何提升Python Tkinter GUI窗口中图标的分辨率?
Tkinter窗口图标像素化问题解决方法
问题描述
我正在通过小任务学习Python,编写了一个Tkinter GUI程序,但运行时窗口角落的图标出现严重像素化,任务栏中的图标却正常。我的图标是50×50尺寸的PNG格式,尝试过搜索解决方案但没找到有效方法,求解决。
附上代码:
from tkinter import * count = 0 def click(): global count count += 1 print("You have clicked the button "+str(count)+" Times") Window = Tk() Photo = PhotoImage(file="Pig2.png") Like_Button = PhotoImage(file="Like-Button2.png") Window.geometry("600x600") Window.title("The Ultimate GUI Program") Icon = PhotoImage(file="AngryBird.png") Window.iconphoto(True,Icon) button = Button(Window, text="Click me", command=click, font=("Comic Sans,",10,"bold"), fg="Red", bg="black", activeforeground="Red", activebackground="black", image=Like_Button, compound="bottom") button.place(x=50,y=50) Window.config(background="white") Label = Label(Window, text="You are using the best program ever!", font=("Arial",10,"bold"), fg="red", bg="white",relief=RAISED,bd=10, padx=10, pady=10,image=Photo, compound="bottom") Label.place(x=170,y=170) # -Placing the image in a specifed place Window.mainloop() # - Displays the window on the computer screen
解决方法
Tkinter的iconphoto()方法在处理窗口标题栏图标时会自动缩放图片,单一尺寸的PNG缩放后易出现像素化。以下是几个可行方案:
使用多尺寸ICO格式文件
Windows系统的窗口标题栏图标通常需要多种尺寸(如16×16、32×32),任务栏会匹配对应尺寸显示。将图标制作成包含多尺寸的ICO文件,改用iconbitmap()加载:# 替换原iconphoto代码 Window.iconbitmap("AngryBird.ico")注意ICO文件需包含至少16×16的尺寸,这是窗口标题栏常用大小,避免缩放失真。
手动缩放PNG到目标尺寸
若坚持用PNG,先将图片缩放到窗口标题栏常用的16×16尺寸再加载:Icon = PhotoImage(file="AngryBird.png") # 按比例缩放到16x16 Icon = Icon.subsample(int(Icon.width()/16), int(Icon.height()/16)) Window.iconphoto(True, Icon)这种方式通过比例缩小减少像素损失。
用Pillow库平滑缩放
安装Pillow库(pip install pillow)后,用其LANCZOS采样算法缩放图片,能更好保留清晰度:from PIL import Image, ImageTk # 加载并缩放到16x16 img = Image.open("AngryBird.png") img = img.resize((16, 16), Image.Resampling.LANCZOS) Icon = ImageTk.PhotoImage(img) Window.iconphoto(True, Icon)
内容的提问来源于stack exchange,提问作者Underflow
相关产品推荐
相关产品推荐

