How i can solve this problem in Python code (TKinter, Pillow, customtkinter) - python

I'm trying to add an image to Customtkinter Buttom, but an error occurs
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()
this code generate the following error:
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'
Can anybody help me?

It looks like you are encountering an error when trying to add an image to a CTkButton widget in the customtkinter module.
The error message mentions that the given image is not a CTkImage, but a PIL.ImageTk.PhotoImage.
To fix this issue, you can try the following:
Use the CTkImage class to create an image object instead of the PIL.ImageTk.PhotoImage class. You can do this by using the CTkImage.open() method to open the image file, like this:
python_image = customtkinter.CTkImage.open('user_icon.png')
I hope this suggestion will help you.

Latest version of customtkinter accepts CTkImage only for image option of its widgets:
...
python_image = customtkinter.CTkImage(Image.open("user_icon.png"))
customtkinter.CTkButton(master=main, image=python_image).pack()
...

Related

I was creating a image with PhotoImage and this error happened

***Error message :
Traceback (most recent call last):
File "C:/Users/gurse/Desktop/Khanda/Khanda.py", line 3, in <module>
label = Label(x, image=PhotoImage(file=r"C:\Users\gurse\Desktop\Khanda"))
File "C:\Users\gurse\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 4062, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\gurse\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 4007, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "C:\Users\gurse\Desktop\Khanda": permission denied *****
My current code :
from tkinter import *
x = Tk()
label = Label(x, image=PhotoImage(file=r"C:\Users\gurse\Desktop\Khanda"))
And the backslashes turn into a Y with 2 lines across it.
That error says that it can't reach the image.
In this case, you have put only the path of the image, but the image name isn't included in it.
To resolve, you have to put also the name of the image in the path like:
r"C:\Users\gurse\Desktop\Khanda\TestImage.png
A small advice -> PhotoImage takes only a few extensions for images (ie. jpeg will occur an error)
I hope that I've been clear ;)
EDIT:
The user acw1668 isn't wrong: you have to use the method mainloop() to show the window with the widgets
According to the information in the traceback, "C:\Users\gurse\Desktop\Khanda" is a directory. So trying to open a directory as a file will raise the exception.
So you need to pass a path of an image file instead, like "C:\Users\gurse\Desktop\Khanda\sample.png".
However since you pass the result of PhotoImage(...) to image option directly, the image will be garbage collected because there is no variable references it. So you need to use a variable to store the result of PhotoImage(...).
Also you need to call grid() or pack() or place() on the label otherwise it won't show up.
Finally you need to call x.mainloop() otherwise the program will exit immediately.
Below is an example code based on yours:
from tkinter import *
x = Tk()
image = PhotoImage(file="C:/Users/gurse/Desktop/sample.png")
label = Label(x, image=image)
label.pack()
x.mainloop()

Can someone explain to me why pyautogui TypeError: cannot unpack non-iterable NoneType object

I'm trying to create a bot that recognizes an image on screen and to be able to click on that image. However, when prompting the bot to click on the image, I am prompted with TypeError: cannot unpack non-iterable NoneType object.
import pyautogui as pg
import keyboard
import time
import pytesseract as tess
from PIL import Image
if pg.locateOnScreen('follow1.png', confidence=0.5) != None:
pg.click('follow1.png')
However, the bot can recognize the image on screen but fails to click on it.
import pyautogui as pg
import keyboard
import time
import pytesseract as tess
from PIL import Image
if pg.locateOnScreen('follow1.png', confidence=0.5) != None:
pg.print('found it!')
How can the script recognize the image on screen but fail to click on it?
I ran into this issue, too. I finally found out the reason was that the icon on the screen has changed due to software update. So I used a new snapshot to repalce the old one. And it worked!
pyautogui.click('D:/pp/video/3/edit.png')
Traceback (most recent call last):
File "", line 1, in
File "D:\Users\cordiero\PycharmProjects\untitled\video\lib\site-packages\pyautogui_init_.py", line 598, in wrapper
returnVal = wrappedFunction(*args, **kwargs)
File "D:\Users\cordiero\PycharmProjects\untitled\video\lib\site-packages\pyautogui_init_.py", line 980, in click
x, y = _normalizeXYArgs(x, y)
TypeError: cannot unpack non-iterable NoneType object
pyautogui.click('D:/pp/video/3/edit.png')
I am pretty new, so this might not work, but what I did was change this in the code:
From: pyautogui.click('Image.png')
To: pyautogui.click(pyautogui.locateOnScreen('Image.png'))
And it worked for me, hope it also does for you!

How do I resolve 'Contract' object has no attribute 'filter', in PIL ImageEnhance module?

I'm having an issue with my code in production. It works locally- I'm not sure how to troubleshoot the issue.
From what I can tell, PIL is the same version in both environments. The Image module works as expected both locally and in production- ImageEnhancement is causing issues.
Locally, the following code works as expected.
from PIL import Image
from PIL import ImageEnhancement
image = Image.open("a.jpg")
newImage = ImageEnhance.Contrast(image)
newImage.enhance(1.5)
newImage.save("newImage.jpg")
However when trying this in my production environment, I get an error:
Traceback (most recent call last):
File "analyse.py", line 95, in <module>
processedImage = ImageEnhance.Sharpness(processedImage)
File "/usr/lib/python2.7/dist-packages/PIL/ImageEnhance.py", line 97, in __init__
self.degenerate = image.filter(ImageFilter.SMOOTH)
AttributeError: 'Contrast' object has no attribute 'filter'
Class Contrast doesn't create image but object which can change image. And enhance() creates new image.
from PIL import Image
from PIL import ImageEnhance
image = Image.open("a.jpg")
enhancer = ImageEnhance.Contrast(image)
new_image = enhancer.enhance(1.5)
new_image.save("newImage.jpg")

_tkinter.TclError: image "..." doesn't exist

I know that this question has already been asked several times, but I still couldn't figure out the answer to my problem. I keep getting the same error and don't know how to solve it.
This is my code:
from Tkinter import *
from PIL import Image, ImageTk
import os
window = Tk()
i = Image.open(pathToImage)
if os.path.isfile(pathToImage):
print 'image exists'
else:
print 'image does not exits'
label=Label(window, image=i)
label.pack()
window.mainloop()
It says that the image exists at the indicated path, but I keep getting this error message:
Traceback (most recent call last):
File "ImageTest.py", line 31, in <module>
label=Label(window, image=i)
File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2597, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=640x480 at 0x36DF278>" doesn't exist
I could not figure out how to solve this problem. Any help would be appreciated!
You should use PhotoImage instance as image value. Also, you need to keep the reference of your image.
im = Image.open(pathToImage)
ph = ImageTk.PhotoImage(im)
label = Label(window, image=ph)
label.image=ph #need to keep the reference of your image to avoid garbage collection
A quick hacky fix is to provide the PhotoImage with the correct master:
i = ImageTk.PhotoImage(pathToImage, master=window)
It seems to be an Anaconda - Spyder - Iphyton problem.
Solution is here:
_tkinter.TclError: image "pyimage" doesn't exist

how to display HSV image - tkinter, python 2.7

I'm converting an RGB image to HSV, and trying to display the same in a Label. But I'm getting error.
My code snippet is:
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
imgthresh=Image.open(imgthresh)
re_hsv=imhsv.resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(windo, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
And my error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "E:\python\track\guinew.py", line 215, in hsv_img
imhsv=Image.open(imgthresh)
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\System\lib\site-packages\PIL\Image.py", line 1956, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'
So how to display the HSV image, is there any other way then what i have tried? Any suggestions are welcome!
Thanks in advance!
The error is thrown when you call Image.open(imgthresh), because Image.open expects a file-like object, but imgthresh is a Numpy array.
Try removing that line altogether.
EDIT: Here's a complete version that works (on my machine):
from PIL import Image, ImageTk
from Tkinter import Tk, Label, SOLID
import cv2
import numpy as np
img = np.array(Image.open('some-file.png'))
window = Tk()
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
re_hsv=Image.fromarray(imghsv).resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(window, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
hsv_img()
window.mainloop()
I had to rename some things, as well as add a call to Image.fromarray when you resize to 360x360.
It seems like most of the confusion stems from different numpy/PIL/OpenCV/Tkinter image formats. You might find this conversion guide useful, though it's slightly out of date.

Categories