[英]How i can solve this problem in Python code (TKinter, Pillow, customtkinter)
我正在嘗試將圖像添加到 Customtkinter Buttom,但出現錯誤
import sqlite3
from tkinter import \*
import customtkinter
from tkinter import ttk
from PIL import Image, ImageTk
customtkinter.set_appearance_mode('dark')
customtkinter.set_default_color_theme('blue')
\#Create a Ctk instance(app)
main = customtkinter.CTk()
main.geometry("400x240")
main.resizable(width=False, height=False)
\#Username Frame
username_tittle = customtkinter.CTkLabel(master=main, text='Username:').place(relx=0.2, rely= 0.3)
username_box = customtkinter.CTkEntry(master=main, width=150)
username_box.place(relx=0.43, rely=0.3)
python_image = ImageTk.PhotoImage(Image.open('user_icon.png'), Image.ANTIALIAS, )
but = customtkinter.CTkButton(master=main, image=python_image).pack()
此代碼生成以下錯誤:
c:\\Users\\claud\\OneDrive\\Documentos\\meuusprojetos\\Login\\main.py:19: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use LANCZOS or Resampling.LANCZOS instead.
python_image = ImageTk.PhotoImage(Image.open('user_icon.png'), Image.ANTIALIAS, )
CTkButton Warning: Given image is not CTkImage but \<class 'PIL.ImageTk.PhotoImage'\>. Image can not be scaled on HighDPI displays, use CTkImage instead.
Traceback (most recent call last):
File "c:\\Users\\claud\\OneDrive\\Documentos\\meuusprojetos\\Login\\main.py", line 20, in \<module\>
but = customtkinter.CTkButton(master=main, image=python_image).pack()
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 106, in __init__
self.\_draw()
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 243, in \_draw
self.\_update_image() # set image
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 154, in \_update_image
self.\_image_label.configure(image=self.\_image.create_scaled_photo_image(self.\_get_widget_scaling(),
AttributeError: 'PhotoImage' object has no attribute 'create_scaled_photo_image'
有誰能夠幫我?
看起來您在嘗試將圖像添加到customtkinter模塊中的CTkButton小部件時遇到錯誤。
錯誤消息提到給定圖像不是CTkImage ,而是PIL.ImageTk.PhotoImage
。
要解決此問題,您可以嘗試以下操作:
使用CTkImage class 創建圖像 object 而不是PIL.ImageTk.PhotoImage
class。您可以通過使用CTkImage.open()方法打開圖像文件來執行此操作,如下所示:
python_image = customtkinter.CTkImage.open('user_icon.png')
我希望這個建議對你有所幫助。
最新版本的customtkinter
僅接受CTkImage
作為其小部件的image
選項:
...
python_image = customtkinter.CTkImage(Image.open("user_icon.png"))
customtkinter.CTkButton(master=main, image=python_image).pack()
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.