求助:为CustomTkinter按钮添加图片失败,提示需使用CTkImage
错误提示已经明确说明原因:CTkButton不接受PIL.ImageTk.PhotoImage类型的图片,必须使用customtkinter自带的CTkImage类,它能适配高DPI显示器的缩放需求。
修正步骤:
- 从customtkinter导入
CTkImage类 - 使用
CTkImage包装PIL打开的图片对象,替代ImageTk.PhotoImage - 可通过
size参数设置图片尺寸,匹配按钮的宽高
修正后的代码:
import tkinter import customtkinter from PIL import Image customtkinter.set_appearance_mode("System") customtkinter.set_default_color_theme("blue") app = customtkinter.CTk() wdth = app.winfo_screenwidth() hgt = app.winfo_screenheight() app.geometry("%dx%d" % (wdth, hgt)) def button_function(): print("button pressed") # 用CTkImage包装PIL图片,可设置size适配按钮尺寸 img1 = customtkinter.CTkImage(light_image=Image.open(r"C:\Users\Vedant\Desktop\py project\pizzalogo-removebg-preview.png"), dark_image=Image.open(r"C:\Users\Vedant\Desktop\py project\pizzalogo-removebg-preview.png"), size=(500, 200)) # 尺寸可与按钮宽高匹配 button = customtkinter.CTkButton(master=app, image=img1, text="", width=500, height=200, command=button_function, compound='left') button.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) app.mainloop()
说明:
CTkImage需要分别传入light_image和dark_image,如果不需要区分明暗模式,两张图传同一个即可size参数用来指定图片显示的尺寸,建议和按钮的width、height保持一致,避免拉伸变形
内容的提问来源于stack exchange,提问作者DarkKnight263
相关产品推荐
相关产品推荐

