Меню

From pil import image imagetk ошибка

Hello Geeks! I hope all are doing great. So today, in this article, we will solve ImportError: Cannot Import Name. But, before that, we understand in which circumstances this error is raised and what are the main reasons for it and then will try to find possible solutions for them. So, Let’s get started.

ImportError occurs when a file cannot load the module, its classes, or methods in a python file. Now, there may be several reasons for this inability to load a module or its classes, such as;

  • The imported module is not imported.
  • The imported module is not created.
  • Module or Class names are misspelled.
  • Imported class is unavailable in certain library
  • Or, the imported class is in circular dependency.

There may be more scenarios in which the importerror occurs. But in this article, we will only focus on the last one, i.e., The imported class is in a circular dependency.

To learn more about other reasons for the error, you can visit another article by us, i.e., Import-classes-from-another-file-in-python.

Circular Dependency

So, sometimes it happens that we imported two or modules in our file, and their existence depends on each other. In simples words, we can say that circular dependency is a condition in which two or more modules are interdependent. Now, when this happens, neither of the modules can successfully be imported, resulting in the given error. Let’s see an example to get a better understanding of it.

file1.py
from file2 import B
class A:
    b_obj = B()
file2.py
from file1 import A
class B:
    A_obj = A()

So, now in the above example, we can see that initialization of A_obj depends on file1, and initialization of B_obj depends on file2. Directly, neither of the files can be imported successfully, which leads to ImportError: Cannot Import Name. Let’s see the output of the above code.

Traceback (most recent call last):
  File "C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile2.py", line 1, in <module>
    from file1 import A
  File "C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile1.py", line 1, in <module>
    import file2
  File "C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile2.py", line 1, in <module>
    from file1 import A
ImportError: cannot import name 'A' from partially initialized module 'file1' (most likely due to a circular import) (C:UsersRishav RajDocumentsPythonPoolCircular Dependencyfile1.py)

Recommended Reading | Python Circular Import Problem and Solutions

Solving ImportError: Cannot Import Name

So, if you understood the core reason for the error, it is not difficult to solve the issue, and I guess most of you have already got the answer till now. Yes, the solution to this is that you can only avoid doing that. The above-given code results from a lousy programming approach, and one should avoid doing that. However, you can achieve your goal by maintaining a separate file for initializing the object.

file1.py
file2.py
file3.py
from file1 import A
from file2 import B

A_obj = A()
B_obj = B()

Example 1: ImportError cannot import name in flask

from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
    return "Hello World!"
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, debug=True)

Output:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from flask import Flask
  File "/home/pi/programs/flask.py", line 1, in <module>
    from flask import Flask
ImportError: cannot import name Flask

The above-given error is raised as the flask is not installed in your system. To solve the error, you need to install it first and then import it. To install it, use the following command.

apt-get install python3-flask

Example 2: ImportError cannot import name in imagetk from pil

# create a class called Person
# create init method
# 2 attributes (name, and birthdate)
# create an object from the Person class

from PIL import Image, ImageTK
import datetime
import tkinter as tk

# create frame
window = tk.Tk()

# create frame geometry
window.geometry("400x400")

# set title of frame
window.title("Age Calculator App")



# adding labels
name_label = tk.Label(text="Name")
name_label.grid(column=0, row=0)

year_label = tk.Label(text="Year")
year_label.grid(column = 0, row = 1)

month_label = tk.Label(text="Month")
month_label.grid(column = 0, row = 2)

day_label = tk.Label(text="Day")
day_label.grid(column = 0, row = 3)


# adding entries
name_entry = tk.Entry()
name_entry.grid(column=1, row=0)

year_entry = tk.Entry()
year_entry.grid(column=1, row=1)

month_entry = tk.Entry()
month_entry.grid(column=1, row=2)

day_entry = tk.Entry()
day_entry.grid(column=1, row=3)


def calculate_age():
    year = int(year_entry.get())
    month = int(month_entry.get())
    day = int(day_entry.get())
    name = name_entry.get()
    person = Person(name, datetime.date(year, month, day))
    text_answer = tk.Text(master=window, wrap=tk.WORD, height=20, width=30)
    text_answer.grid(column= 1, row= 5)
    answer = "{name} is {age} years old!".format(name=person.name, age=person.age())
    is_old_answer = " Wow you are getting old aren't you?"
    text_answer.insert(tk.END, answer)
    if person.age() >= 50:
        text_answer.insert(tk.END, is_old_answer)


calculate_button = tk.Button(text="Calculate Age!", command=calculate_age)
calculate_button.grid(column=1, row=4)


class Person:
    def __init__(self, name, birthdate):
        self.name = name
        self.birthdate = birthdate

    def age(self):
        today = datetime.date.today()
        age = today.year - self.birthdate.year
        return age

image = Image.open('LockVectorDaily.jpg')
image.thumbnail((100, 100), Image.ANTIALIAS)
photo = tk.PhotoImage(file=image)
label_image = tk.Label(image=image)
label_image.grid(column=1, row=0)


window.mainloop()

Output:

from PIL import Image, ImageTK 
ImportError: cannot import name 'ImageTK' 

Here, the error occurs as Python is unable to import ImageTK. Now, the reason behind the error is unknown, but you can solve it by importing them separately using the following command.

import PIL
from PIL import TkImage
from PIL import Image

Example 3: Python ImportError: cannot import name _version_

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/requests_oauthlib/__init__.py", line 1, in
  <module>
    from .oauth1_auth import OAuth1
  File "/usr/lib/python2.7/site-packages/requests_oauthlib/oauth1_auth.py", line 10, in  
  <module>
    from requests.utils import to_native_string
  File "/usr/lib/python2.7/site-packages/requests/utils.py", line 23, in <module>
    from . import __version__
ImportError: cannot import name __version__

Check the __init__.py at root dir. Openpyxl read this information from the .constrants.JSON file. However, PyInstaller somehow can’t make it right. I would you write a __version__.py file by yourself and replace them in the __init__.py.

import json
import os


# Modified to make it work in PyInstaller
#try:
#    here = os.path.abspath(os.path.dirname(__file__))
#    src_file = os.path.join(here, ".constants.json")
#    with open(src_file) as src:
#        constants = json.load(src)
#        __author__ = constants['__author__']
#        __author_email__ = constants["__author_email__"]
#        __license__ = constants["__license__"]
#        __maintainer_email__ = constants["__maintainer_email__"]
#        __url__ = constants["__url__"]
#        __version__ = constants["__version__"]
#except IOError:
#    # packaged
#    pass

__author__ = 'See AUTHORS'
__author_email__ = '[email protected]'
__license__ = 'MIT/Expat'
__maintainer_email__ = '[email protected]'
__url__ = 'http://openpyxl.readthedocs.org'
__version__ = '2.4.0-a1'

"""Imports for the openpyxl package."""
from openpyxl.compat.numbers import NUMPY, PANDAS
from openpyxl.xml import LXML

from openpyxl.workbook import Workbook
from openpyxl.reader.excel import load_workbook
print('You are using embedded openpyxl... 2.4.0-a1 ...')

Q1) How do you fix an importerror in Python?

It differs according to the mistake you have made.
All the possible solutions are discussed in the article refer it.

Q2) What is a name error in Python?

Name error is raised when the system cannot identify the variables used.

Conclusion

So, today in this article, we have seen the main reasons for ImportError: Cannot Import Name. We have seen the concept of circular dependency and how it affects our code. In the end, we have seen what things we should avoid getting into any such condition are.

I hope this article has helped you. Thank You.

Other Errors You Might Face

  • [Fixed] Module Seaborn has no Attribute Histplot Error

    [Fixed] Module Seaborn has no Attribute Histplot Error

    January 18, 2023

  • [Fixed] JavaScript error: IPython is Not Defined

    [Fixed] JavaScript error: IPython is Not Defined

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] “io.unsupportedoperation not readable” Error

    [Fixed] “io.unsupportedoperation not readable” Error

    by Rahul Kumar YadavJanuary 18, 2023

  • [Fixed] “Index Object Has No Attribute tz_localize” Error

    [Fixed] “Index Object Has No Attribute tz_localize” Error

    by Rahul Kumar YadavJanuary 18, 2023

@B.Goode
Sorry, I should not have pulled you up on that after all the help you have given me in the past!

My Python 2 code is shown below. I say mine, what I mean is the code I use. I have kept all my comments in the start to give credit to the person who posted it originally. I have however made extensive changes to it by adding code for the Pan/Tilt hat and adding buttons to allow easy control of the camera, including some fixed positions (all my own work!)

I have completely failed though to get it to run on my much preferred Python 3, so I stuck with this Python 2 version, which worked well until my 3B+ that I loaded with Stretch arrived a few days ago.

(My notes at the start of the Program, show that it was the cv2 command that I could not find a Python 3 equivalent for)

Code: Select all

# -*- coding: utf-8 -*-
# Created i La Selva 18-mars-04 15:15
# Modified i La Selva 19-Januari-07  16:40
# I got this program off the RPi Forum in early Jan 2019
# https://www.raspberrypi.org/forums/viewtopic.php?f=32&t=230454&p=1413261#p1413261
# Disappointing thing is that this program is written in Python2
# Need to try to convert it to Python 3 but the command cv2 on line 6
# of the program is difficult!
# Started to add Pan / Tilt commands on 13th Jan 2019

from PIL import Image, ImageTk
from pantilthat import *
import Tkinter as tk
import argparse
import time
import datetime
import cv2
import os
import re
import shutil
import smtplib
import subprocess
import urllib
import RPi.GPIO as GPIO
import threading
import picamera
import imutils

from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from email.mime.image import MIMEImage

fromaddr = "************@gmail.com"
toaddr = "***********"
mailpass = "-----------"

device = "Pi03 Cam "

path = "/home/pi/"
moveto = "/home/pi/Pictures/"  # was "/home/pi/Pictures/saved/"


bilder = "No Image.jpg"
flag = 0
delete_flag = 0
xaxis = 0
yaxis = 0

os.system("sudo modprobe bcm2835-v4l2") # to recognize PiCamera as video0

def do_picam(app):
    global shot
    global texte
    global texmed
    global delete_flag
    global txt_display
    camera = picamera.PiCamera()
    #camera.awb_mode = 'auto'
    camera.brightness = 50
    camera.resolution = (2592, 1944)
    camera.rotation = 180
    #data = time.strftime("%y-%b-%d_(%H%M%S)")
    data = time.strftime("%d %b %Y_(%H-%M-%S)")
    texte = "picture take at: " + data    
    camera.start_preview()
    camera.capture('%s.jpg' % data)
    camera.stop_preview()
    camera.close() # close Picamera to free resources  to restart the video stream
    shot = '%s.jpg' % data
    #dagtid = time.strftime("%y-%b-%d (%H:%M)")
    dagtid = time.strftime("%d-%b-%y (%H:%M)")
    texte = "picture take:" + time.strftime("%y-%b-%d_(%H%M%S)")
    texmed = device + dagtid
    app.showImg()
    app.textBox.delete("1.0", tk.END)
    app.textBox.insert(tk.END,shot)
    app.textBox.configure(bg="dodgerblue")
    app.textBox.update_idletasks()
    delete_flag = 1
    app.vs.open(0) # restarting video stream from Pi Camera
    app.enable_buttons()
    txt_display = " " + shot[0:18]

def do_sendMail(app):   
    mail = MIMEMultipart()
    mail['Subject'] =   str(texmed)
    mail['From'] = fromaddr
    mail['To'] = toaddr
    mail.attach(MIMEText(texte, 'plain'))

    attachment = open(shot, 'rb')
    image = MIMEImage(attachment.read())
    attachment.close()
    mail.attach(image)
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(fromaddr, mailpass)
    text = mail.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()
    app.textBox.delete("1.0", tk.END)
    app.textBox.insert(tk.END,txt_display + "  MAILED OK")
    app.textBox.update_idletasks() 
    app.enable_buttons()
    
class Application:
    def __init__(self, output_path = "./"):
        """ Initialize application which uses OpenCV + Tkinter. It displays
            a video stream in a Tkinter window and stores current snapshot on disk """
        self.vs = cv2.VideoCapture(0) # capture video frames, 0 is your default video camera
        self.output_path = output_path  # store output path
        self.current_image = None  # current image from the camera
        self.root = tk.Tk()  # initialize root window
        defaultbg = self.root.cget('bg') # set de default grey color to use in labels background
        w = 930 # width for the Tk root
        h = 535 # height for the Tk root
        self.root .resizable(0, 0)
        ws = self.root .winfo_screenwidth() # width of the screen
        hs = self.root .winfo_screenheight() # height of the screen
        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)
        self.root .geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.root.title("Live Video Feed")  # set window title
        self.root.protocol('WM_DELETE_WINDOW', self.destructor)

        self.panel = tk.Label(self.root)  # initialize Main Image panel
        self.panel.grid(row=0, rowspan=15, column=1, padx=4, pady=6, columnspan=6)

        self.labPic= tk.Label(self.root, bg="grey70")  # initialize Small Image panel
        self.labPic.grid(row=0, column=7,  padx=5, pady=6) # was (row=5, column=34,  padx=4, pady=6)

        self.textBox = tk.Text(self.root, height=1, width=28, font=('arial narrow', 10, 'bold'), bg="green",fg="white")
        self.textBox.grid(row=1, rowspan=5, column=7, padx=3)
        self.textBox.insert(tk.END, "READY")

        self.botShoot = tk.Button(self.root,width=6, font=('arial narrow', 14, 'normal'),  text="Capture", activebackground="#00dfdf" )
        self.botShoot.grid(row=8, column=7)
        self.botShoot.configure(command=self.picam)

        self.botSave = tk.Button(self.root,width=10, font=('arial narrow', 14, 'normal'),  text="Save Picture", activebackground="#00dfdf" )
        self.botSave.grid(row=9, column=7, pady=1) # was (row=10, column=34, pady=1)
        self.botSave.configure(command=self.movepic,state = "disabled")
        
        self.botMail = tk.Button(self.root,width=10, font=('arial narrow', 14, 'normal'),  text="email Picture", activebackground="#00dfdf" )
        self.botMail.grid(row=10, column=7, pady= 1) # was (row=8, column=34, pady= 1)
        self.botMail.configure(command=self.sendMail,state = "disabled")

        self.botRadera = tk.Button(self.root,width=10, font=('arial narrow', 14, 'normal'),  text="Delete Picture", activebackground="#00dfdf" )
        self.botRadera.grid(row=11, column=7, pady=1) # was (row=9, column=34, pady=1)
        self.botRadera.configure(command=self.radera, state = "disabled")

        self.botQuit = tk.Button(self.root,width=4,font=('arial narrow', 14, 'normal'), text="CLOSE", activebackground="#00dfdf")
        self.botQuit.grid(row=12,column=7)
        self.botQuit.configure(command=self.destructor) 
                
        self.botUp = tk.Button(self.root,width=2, font=('arial narrow', 14, 'normal'),  text="Up", activebackground="#00dfdf" )
        self.botUp.grid(row=15, column=2)
        self.botUp.configure(command=self.camUp, repeatdelay=100, repeatinterval=100)
        
        self.botDown = tk.Button(self.root,width=4, font=('arial narrow', 14, 'normal'),  text="Down", activebackground="#00dfdf" )
        self.botDown.grid(row=15, column=3)
        self.botDown.configure(command=self.camDown, repeatdelay=100, repeatinterval=100)
        
        self.botLeft = tk.Button(self.root,width = 0, font=('arial narrow', 14, 'normal'),  text="Left", activebackground="#00dfdf" )
        self.botLeft.grid(row=15, column=1)
        self.botLeft.configure(command=self.camLeft, repeatdelay=100, repeatinterval=100)

        self.botRight = tk.Button(self.root,width=4, font=('arial narrow', 14, 'normal'),  text="Right", activebackground="#00dfdf" )
        self.botRight.grid(row=15, column=4)
        self.botRight.configure(command=self.camRight, repeatdelay=100, repeatinterval=100)

        self.botClock = tk.Button(self.root,width=4, font=('arial narrow', 14, 'normal'),  text="Clock", activebackground="#00dfdf" )
        self.botClock.grid(row=15, column=5)
        self.botClock.configure(command=self.camClock)
        
        self.botCeiling = tk.Button(self.root,width=4, font=('arial narrow', 14, 'normal'),  text="Ceiling", activebackground="#00dfdf" )
        self.botCeiling.grid(row=15, column=6)
        self.botCeiling.configure(command=self.camCeiling)

        self.botCeiling = tk.Button(self.root,width=4, font=('arial narrow', 14, 'normal'),  text="Door", activebackground="#00dfdf" )
        self.botCeiling.grid(row=15, column=7)
        self.botCeiling.configure(command=self.camDoor)
                     
        self.video_loop()
        
    def video_loop(self):
        global test
        global flag
        """ Get frame from the video stream and show it in Tkinter """
        ok, frame = self.vs.read()  # read frame from video stream
        if ok:  # frame captured without any errors
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)  # convert colors from BGR to RGBA
            cv2image = imutils.rotate_bound(cv2image, 180) # rotate image
            self.current_image = Image.fromarray(cv2image)  # convert image for PIL
            imgtk = ImageTk.PhotoImage(image=self.current_image)  # convert image for tkinter
            test = cv2image
            self.panel.imgtk = imgtk  # anchor imgtk so it does not be deleted by garbage-collector
            self.panel.config(image=imgtk)  # show the image

        self.root.after(30, self.video_loop)  # call the same function after 30 milliseconds
        if flag ==0:
            flag = 1
            self.show_thumb()
            
    def snapshot(self):
        imageName = 'cv-' + time.strftime("%Y-%b-%d_(%H%M%S)")+ '.jpg'
        cv2.imwrite(imageName,test)

    def picam(self):        
        self.disable_buttons()
        self.vs.release() # release the camera to get all resources
        t = threading.Thread(target=do_picam, args=(self,))
        t.start()
        
    def showImg(self):
        image = Image.open(shot)          
        image = image.resize((252,195),Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)       
        self.labPic.configure(image=photo)
        self.labPic.image=photo
        self.root.update_idletasks()

    def show_thumb(self) :
        image = Image.open(bilder)          
        image = image.resize((252,195),Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)       
        self.labPic.configure(image=photo)
        self.labPic.image=photo
        self.root.update_idletasks()

    def sendMail(self):
        global xaxis
        t = threading.Thread(target=do_sendMail, args=(self,))
        t.start()
        self.disable_buttons()
        self.textBox.delete("1.0", tk.END)
        self.textBox.insert(tk.END,"SENDING PICTURE BY MAIL")
        self.textBox.update_idletasks()

    def camRight(self):
        global xaxis
        global yaxis
        self.botLeft.configure(state="normal")
        print ('x axis = ', xaxis, ": y axis = ", yaxis)
        xaxis = xaxis -1
        if xaxis < -90:
            xaxis = -90
            self.botRight.configure(state="disabled")
        pan(xaxis)
                
    def camLeft(self):
        global xaxis
        global yaxis
        self.botRight.configure(state="normal")
        print ('x axis = ', xaxis, ": y axis = ", yaxis)
        xaxis = xaxis +1
        if xaxis > 90:
            xaxis = 90
            self.botLeft.configure(state="disabled")
        pan(xaxis)
        
    def camUp(self):
        global xaxis
        global yaxis
        self.botDown.configure(state="normal")
        print ('x axis = ', xaxis, ": y axis = ", yaxis)
        yaxis = yaxis -1
        if yaxis < -90:
            yaxis = -90
            self.botUp.configure(state="disabled")
        tilt(yaxis)

    def camDown(self):
        global xaxis
        global yaxis
        self.botUp.configure(state="normal")
        print ('x axis = ', xaxis, ": y axis = ", yaxis)
        yaxis = yaxis + 1
        if yaxis > 90:
            yaxis = 90
            self.botDown.configure(state="disabled")
        tilt(yaxis)

    def camClock(self):
        global xaxis
        global yaxis
        self.botUp.configure(state="normal")
        self.printCoords
        print 'x axis = ', xaxis, ": y axis = ", yaxis
        #self.botDown.configure(state="disabled")
        xaxis = 0
        yaxis = 11
        tilt(yaxis)
        pan(xaxis)

    def camCeiling(self):
        global xaxis
        global yaxis
        self.botUp.configure(state="normal")
        print ('x axis = ', xaxis, ": y axis = ", yaxis)
        #self.botDown.configure(state="disabled")
        xaxis = 21
        yaxis = -58
        tilt(yaxis)
        pan(xaxis)
        
    def camDoor(self):
        global xaxis
        global yaxis
        self.botUp.configure(state="normal")
        print ('x axis = ', xaxis, ": y axis = ", yaxis)
        #self.botDown.configure(state="disabled")
        xaxis = 31
        yaxis = -2
        tilt(yaxis)
        pan(xaxis)
        
    def printCoords(self):
        # Python 3 version print ('x axis = ', xaxis, ": y axis = ", yaxis)
        print ('x axis = ', xaxis, ": y axis = ", yaxis)

    def movepic(self):
        global delete_flag
        pic= shot
        src = path+pic
        dst = moveto+pic
        shutil.move(src,dst)
        self.textBox.delete("1.0", tk.END)
        self.textBox.insert(tk.END,txt_display + "   SAVED")
        self.textBox.configure(bg="darkorange")
        self.textBox.update_idletasks()
        self.botMail.configure(state="disabled")
        self.botSave.configure(state="disabled")
        self.botRadera.configure(state="disabled")
        delete_flag = 2
                            
    def radera(self):
        global delete_flag
        pic = shot
        os.remove(pic)
        self.textBox.delete("1.0", tk.END)
        self.textBox.insert(tk.END,txt_display + "  DELETED ")
        self.textBox.configure(bg="red")
        self.textBox.update_idletasks()
        delete_flag = 2
        self.botMail.configure(state="disabled")
        self.botSave.configure(state="disabled")
        self.botRadera.configure(state="disabled")
        
    def disable_buttons(self):
        self.botShoot.configure(state="disabled")
        self.botMail.configure(state="disabled")
        self.botSave.configure(state="disabled")
        self.botRadera.configure(state="disabled")
        self.botQuit.configure(state="disabled")

    def enable_buttons(self):
        self.botShoot.configure(state="normal")
        self.botMail.configure(state="normal")
        self.botSave.configure(state="normal")
        self.botRadera.configure(state="normal")
        self.botQuit.configure(state="normal")
        
    def destructor(self):
        if delete_flag == 1 : self.radera()
        self.root.destroy()
        self.vs.release()  # release web camera
        cv2.destroyAllWindows()  # it is not mandatory in this application

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", default="./Pictures",
help="path to output directory to store snapshots (default: current folder")
args = vars(ap.parse_args())

# start the app
pba = Application(args["output"])
pba.root.mainloop()

I am learning tkinter and trying to place an image on a Button, but I cannot get past the import.

My code:

from tkinter import *
from PIL import Image, ImageTk

The error:

No module named 'ImageTk'

Based on a post I saw when researching this I tried
sudo apt-get install python-imaging-tk

which says I already have the latest version.

I am on a Raspberry Pi3, with a new install of Raspbian and I did an upgrade and update to be sure.

Any suggestions?

Here is the output of apt-cache show python-pil requested in a comment below:

Package: python-pil
Source: pillow
Version: 2.6.1-2+deb8u3
Architecture: armhf
Maintainer: Matthias Klose <doko@debian.org>
Installed-Size: 1050
Depends: python (<< 2.8), python (>= 2.7~), python:any (>= 2.7.5-5~), mime-support | python-pil.imagetk, libc6 (>= 2.11), libfreetype6 (>= 2.2.1), libjpeg62-turbo (>= 1.3.1), liblcms2-2 (>= 2.2+git20110628), libtiff5 (>= 4.0.3), libwebp5, libwebpdemux1, libwebpmux1, zlib1g (>= 1:1.1.4)
Suggests: python-pil-doc, python-pil-dbg
Breaks: python-imaging (<< 1.1.7+2.0.0-1.1)
Replaces: python-imaging (<< 1.1.7+2.0.0-1.1)
Provides: python-pillow, python2.7-pil
Multi-Arch: same
Homepage: http://python-pillow.github.io/
Priority: optional
Section: python
Filename: pool/main/p/pillow/python-pil_2.6.1-2+deb8u3_armhf.deb
Size: 277856
SHA256: 9f4e54fbe21fde51c13f4c875a09045a05a61abb55db723c4b09c14ce125eb4d
SHA1: 1e0369561c91e3d8fcaced1027f281ffc05fda32
MD5sum: ec0be47a97ef8aea42211eb1c19ce6bf
Description: Python Imaging Library (Pillow fork)
 The Python Imaging Library (PIL) adds an image object to your Python
 interpreter. You can load images from a variety of file formats, and
 apply a rich set of image operations to them.
 .
 Image Objects:
  o Bilevel, greyscale, palette, true colour (RGB), true colour with
    transparency (RGBA).
  o colour separation (CMYK).
  o Copy, cut, paste operations.
  o Flip, transpose, resize, rotate, and arbitrary affine transforms.
  o Transparency operations.
  o Channel and point operations.
  o Colour transforms, including matrix operations.
  o Image enhancement, including convolution filters.
 .
 File Formats:
  o Full (Open/Load/Save): BMP, EPS (with ghostscript), GIF, IM, JPEG,
    MSP, PDF, PNG, PPM, TIFF, XBM.
  o Read only (Open/Load): ARG, CUR, DCX, FLI, FPX, GBR, GD, ICO, IMT, IPTC,
    MCIDAS, MPEG, PhotoCD, PCX, PIXAR, PSD, TGA, SGI, SUN, TGA, WMF, XPM.
  o Save only: PDF, EPS (without ghostscript).
Description-md5: 7fb415befc961c94ce8c999eb6902e95

hello,
I am trying out PIL for the first time but I cannot add / download it.
Can someone help me with this?

I use pycharm for programming.

this is the code i tried:
import PIL
from PIL import Image, ImageTK

Posts: 7,834

Threads: 148

Joined: Sep 2016

Reputation:
571

rodink

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jan 2020

Reputation:
0

Jan-16-2020, 02:59 PM
(This post was last modified: Jan-16-2020, 03:00 PM by rodink.)

(Jan-16-2020, 02:51 PM)buran Wrote: did you install Pillow?

i think i did
python -m pip install Pillow
Requirement already satisfied: Pillow in c:pythonpython38libsite-packages (7.0.0)

Posts: 7,834

Threads: 148

Joined: Sep 2016

Reputation:
571

Jan-16-2020, 03:00 PM
(This post was last modified: Jan-16-2020, 03:01 PM by buran.)

it’s Pillow, with capital P
using pip:
pip install Pillow

rodink

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jan 2020

Reputation:
0

(Jan-16-2020, 03:00 PM)buran Wrote: it’s Pillow, with capital P
using pip:
pip install Pillow

Same result

pip install Pillow
Requirement already satisfied: Pillow in c:pythonpython38libsite-packages (7.0.0)

Posts: 7,834

Threads: 148

Joined: Sep 2016

Reputation:
571

Jan-16-2020, 03:10 PM
(This post was last modified: Jan-16-2020, 03:10 PM by buran.)

OK, it’s now installed and you should be able to import it (in your code in Pycharm or other IDE).
If you have multiple python installations, make sure that the correct one is set as interpreter in pycharm settings

rodink

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jan 2020

Reputation:
0

(Jan-16-2020, 03:10 PM)buran Wrote: OK, it’s now installed and you should be able to import it (in your code in Pycharm or other IDE).
If you have multiple python installations, make sure that the correct one is set as interpreter in pycharm settings

Collecting PIL

Could not find a version that satisfies the requirement PIL (from versions: )
No matching distribution found for PIL

it did not work

Posts: 7,834

Threads: 148

Joined: Sep 2016

Reputation:
571

Jan-16-2020, 03:22 PM
(This post was last modified: Jan-16-2020, 03:22 PM by buran.)

Hm, I don’t understand what you are doing:

(Jan-16-2020, 02:59 PM)rodink Wrote: i think i did
python -m pip install Pillow
Requirement already satisfied: Pillow in c:pythonpython38libsite-packages (7.0.0)

(Jan-16-2020, 03:04 PM)rodink Wrote: pip install Pillow
Requirement already satisfied: Pillow in c:pythonpython38libsite-packages (7.0.0)

Pillow is already installed for you python3.8 installation at c:pythonpython38

Now you should be able to do in Pycharm:

import PIL
from PIL import Image, ImageTK

given that python3.8 (c:pythonpython38) is set as default interpreter for the project


Note that Pillow is friendly fork of PIL and replaced it long time ago.

rodink

Programmer named Tim


Posts: 5

Threads: 1

Joined: Jan 2020

Reputation:
0

(Jan-16-2020, 03:22 PM)buran Wrote: Hm, I don’t understand what you are doing:

(Jan-16-2020, 02:59 PM)rodink Wrote: i think i did
python -m pip install Pillow
Requirement already satisfied: Pillow in c:pythonpython38libsite-packages (7.0.0)

(Jan-16-2020, 03:04 PM)rodink Wrote: pip install Pillow
Requirement already satisfied: Pillow in c:pythonpython38libsite-packages (7.0.0)

Pillow is already installed for you python3.8 installation at c:pythonpython38

Now you should be able to do in Pycharm:

import PIL
from PIL import Image, ImageTK

given that python3.8 (c:pythonpython38) is set as default interpreter for the project

i just put this in my code:

import PIL
from PIL import Image, ImageTK

it give me this error:

ModuleNotFoundError: No module named ‘PIL’

Posts: 7,834

Threads: 148

Joined: Sep 2016

Reputation:
571

Jan-16-2020, 03:41 PM
(This post was last modified: Jan-16-2020, 03:41 PM by buran.)

Read
https://www.jetbrains.com/help/pycharm/c…reter.html

and setup the interpreter for the project to be python3.8 with Pillow installed

Я не могу понять, как решить проблему с моим кодом, касающимся импорта ImageTK из PIL. Я искал и загружал Подушку разными способами, и ошибка кода все та же.

Traceback (most recent call last):
File "8_Age_Calculator_App.py", line 3, in <module>
from PIL import Image, ImageTK
ImportError: cannot import name 'ImageTK'

Это коды импорта файла

import PIL
from PIL import Image, ImageTK
import tkinter as tk
import datetime

И это код, который пытается импортировать изображение

main_image = Image.open('/Users/Brenden/Documents/Python_OOP/old-people-
running-illo_h.jpg')
main_image.thumbnail((100,100), Image.ANTIALIAS)
main_photo = ImageTK.Photoimage(main_image)
main_label_image = tk.Label(image=main_photo)
main_label.grid(column=1, row=0)

Как я могу решить эту проблему? Я поставлю весь сценарий в комментариях, если кто-то захочет увидеть все это. Спасибо за уделенное время.

4 ответа

Лучший ответ

У вас есть опечатка в модуле, который вы хотите импортировать. k в ImageTk должен быть в нижнем регистре:

from PIL import Image, ImageTk

Это должно решить вашу проблему

И в вашем скрипте есть еще одна опечатка, PhotoImage — CamelCase:

main_photo = ImageTk.PhotoImage(main_image)


5

Jan Steinke
18 Янв 2018 в 09:31

Используйте эти команды для Python 3

 sudo apt-get install python3-pil.imagetk


5

Saurav Kumar
8 Июл 2018 в 07:13

ImageT K — это k (маленькая буква), а не K (заглавная буква)

from PIL import Image, ImageTk


1

Sai Gopi N
13 Апр 2018 в 05:57

Установите его с помощью этой команды.

sudo apt-get install python-imaging-tk


2

usr_11
18 Янв 2018 в 09:22

#python #tkinter

Вопрос:

Когда я попытался добавить кнопку диалогового окна файла, я все время получал такую ошибку:

 _tkinter.TclError: can't use "pyimage1" as iconphoto: not a photo image
 

Это мой код:

 from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
from file_dialog import filedialog

root = Tk()
img = PhotoImage(file='icon.png')

root.geometry("700x500") # the application window size
root.iconphoto(False,img) #application icon
root.title("I need a NAME!") # title of window

def file_dialog():
    root.filename = filedialog.askopenfilename(initialdir="Downloads", title="Select A File To Start", filetypes=(("mp4 files", "*.mp4"),("mov files", "*.mov"),("png files", "*.png"),("jpeg files", "*.jpeg"),("jpg files", "*.jpg")))


def file_dialog_button(app):
    app = app.tk()
    button = app.Button(app, text="Start!", command=file_dialog)
    button.pack(app)

root.mainloop()

print("Succesful Build")

file_dialog()
file_dialog_button()
 

Комментарии:

1. Не удается воспроизвести ошибку.

2. В этом нет никакого смысла, from file_dialog import filedialog ?? Вы уже импортировали filedialog из tkinter

3. @acw1668, когда я запустил код, он выдал ModuleNotFoundError: No module named 'file_dialog'

4. @Дерек, я удалил не относящийся к делу код и просто сосредоточился на iconphoto() нем .

5. Извините @acw1668 Я не критик, я согласен с вами

Ответ №1:

Я внес несколько изменений в ваш код, которые позволяют загружать изображения в значок корневого окна.

from tkinter import * это плохая практика, поэтому я изменил ее на import tkinter as tk и внес необходимые изменения.

Проблема заключалась в том, что вы пытались ссылаться на функции и переменные до того, как они были объявлены.

 import tkinter as tk
from PIL import ImageTk, Image
from tkinter import filedialog

root = tk.Tk()
root.geometry("700x500") # the application window size
root.title("I need a NAME!") # title of window

def file_dialog():
    filename = filedialog.askopenfilename(
        initialdir="Downloads",
        title="Select A File To Start",
        filetypes=(
            ("mp4 files", "*.mp4"),
            ("mov files", "*.mov"),
            ("png files", "*.png"),
            ("jpeg files", "*.jpeg"),
            ("jpg files", "*.jpg")))

    if filename:
        root.img = tk.PhotoImage(file=filename)
        root.iconphoto( False, root.img ) # application icon

app = tk.Toplevel(root)
app.transient( root )
button = tk.Button(app, text="Start!", command=file_dialog)
button.pack(fill = "both", expand = True)

root.mainloop()

print("Successful Build")
 

Комментарии:

1. по крайней мере , вы изменили импорт для tkinter , но зачем импортировать из PIL , если вы его не используете? кроме того, что это за заявление о печати? он будет отображаться только тогда, когда вы закроете окно , а это значит, что он будет больше похож на successful build destruction , в противном случае отличный ответ

Ответ №2:

  1. В соответствии с вашей ошибкой проблема в формате вашего файла, измените формат значка окна tkinter на .ico . Значок может быть только в .ico формате.
  2. Удалите этот from file_dialog import filedialog импорт, вы уже импортировали файловый журнал из tkinter.
  3. Измените окно вашего приложения на TopLevel() окно. Вы можете узнать о них больше здесь
  4. В своем вызове file_dialog_button() вы не передали значение переменной app .

Ваш окончательный код должен выглядеть следующим образом:

 from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog

root = Tk()
img = PhotoImage(file='icon.ico')

root.geometry("700x500") # the application window size
root.iconphoto(False,img) #application icon
root.title("I need a NAME!") # title of window

def file_dialog():
    filename = filedialog.askopenfilename(initialdir="Downloads", title="Select A File To Start", filetypes=(("mp4 files", "*.mp4"),("mov files", "*.mov"),("png files", "*.png"),("jpeg files", "*.jpeg"),("jpg files", "*.jpg")))


def file_dialog_button(app):
    app = Toplevel()
    button = Button(app, text="Start!", command=file_dialog)
    button.pack(app)

print("Succesful Build")

file_dialog()
file_dialog_button('exmaple_name')
root.mainloop()
 

Комментарии:

1. одно небольшое дополнение: я настоятельно не рекомендуем использовать подстановочный знак ( * ) при импорте что-то, вы должны либо импортировать то, что вам нужно, например, from module import Class1, func_1, var_2 и так далее, либо импортировать весь модуль: import module вы также можете использовать псевдоним: import module as md или sth, как это, дело в том, что не все импортное, если вы на самом деле знаете, что Вы делаете; наименование столкновения эту проблему.

2. что в основном означает, что их первая строка должна выглядеть так from tkinter import Tk, Toplevel, Button . также вы либо используете PIL , что означает это ImageTk.PhotoImage , и Image.open() или удаляете этот импорт и добавляете PhotoImage в первую строку импорта: from tkinter import Tk, Toplevel, Button, PhotoImage

#
3 года, 6 месяцев назад

(отредактировано

3 года, 6 месяцев назад)

Темы:

132

Сообщения:

978

Участник с: 11 октября 2013

Коллеги,

пытаюсь запустить

/usr/sbin/image-to-gcode

получаю при попытке скормить в обработку файл png сообщение об ошибке —


Traceback (most recent call last):
  File "/usr/sbin/image-to-gcode", line 828, in <module>
    main()
  File "/usr/sbin/image-to-gcode", line 764, in main
    options = ui(im, nim, im_name)
  File "/usr/sbin/image-to-gcode", line 498, in ui
    import ImageTk
ImportError: No module named ImageTk

Понятное дело, стоит python2-pillow, python-pilkit, LinuxCNC. Но где найти и как поставить ImageTk module?

В итоге выяснилось, что во всем виноват зоопарк питонов и мелочи.
Вариантов решения несколько —
а)
1. скачать с гита git clone https://github.com/robomechs/image-to-gcode.git
2. дать право на исполнение имеющимся там питоновским скриптам
3. vi image-to-gcode и в первой же строке дописать версию питона 2.7
4. запустить и получить удовольствие

б) — этот вариант нужен для вызова утилиты из самого LinuxCNC
1. выполнить схему а),
2. переименовать image-to-gcode.py в vi image-to-gcode
3. скопировать или переместить vi image-to-gcode и autor.py в /usr/sbin/

КАК ВСЕГДА ОГРОМНОЕ СПАСИБО ЗА ОТЗЫВЧИВОСТЬ, ОПЕРАТИВНОСТЬ VS220 & VASEK!!!

vs220

#
3 года, 6 месяцев назад

(отредактировано

3 года, 6 месяцев назад)

Темы:

22

Сообщения:

8090

Участник с: 16 августа 2009

У вас там
питон второй или третий используется?
Для третьего python-pillow поставить

wau

#
3 года, 6 месяцев назад

Темы:

132

Сообщения:

978

Участник с: 11 октября 2013

Если бы. Стоит у меня python-pillow, а результат известный — выше.

vs220

#
3 года, 6 месяцев назад

(отредактировано

3 года, 6 месяцев назад)

Темы:

22

Сообщения:

8090

Участник с: 16 августа 2009

wau
Стоит у меня python-pillow

какому пакету принадлежит /usr/sbin/image-to-gcode

pacman -Qo /usr/sbin/image-to-gcode

?
Ну и ImageTk.py заодно

pacman -Qo /usr/lib/python3.7/site-packages/PIL/ImageTk.py
pacman -Qo /usr/lib/python2.7/site-packages/PIL/ImageTk.py

wau

#
3 года, 6 месяцев назад

(отредактировано

3 года, 6 месяцев назад)

Темы:

132

Сообщения:

978

Участник с: 11 октября 2013

pacman -Qo /usr/sbin/image-to-gcode
/usr/bin/image-to-gcode принадлежит linuxcnc-sim 2.7.14-2

Блин. А оно ведь у меня есть —

pacman -Qo /usr/lib/python3.7/site-packages/PIL/ImageTk.py
/usr/lib/python3.7/site-packages/PIL/ImageTk.py принадлежит python-pillow 6.1.0-1
pacman -Qo /usr/lib/python2.7/site-packages/PIL/ImageTk.py
/usr/lib/python2.7/site-packages/PIL/ImageTk.py принадлежит python2-pillow 6.1.0-1

Но при этом результат выше. Как их подружить?
Если по-простецки сделать —


pip install pillow
ln -s /usr/lib/python3.7/site-packages/PIL/ImageTk.py /usr/sbin/

то сообщение об ошибке меняется (на стадии выбора файла png), но не существенно —


image-to-gcode
Traceback (most recent call last):
  File "/usr/sbin/image-to-gcode", line 828, in <module>
    main()
  File "/usr/sbin/image-to-gcode", line 764, in main
    options = ui(im, nim, im_name)
  File "/usr/sbin/image-to-gcode", line 498, in ui
    import ImageTk
  File "/usr/bin/ImageTk.py", line 31, in <module>
    from . import Image
ValueError: Attempted relative import in non-package

Если же поставить программу отсюда — https://www.cnc-club.ru/forum/viewtopic.php?t=3541, то сообщение об ошибке лаконичнее —


File "/usr/sbin/image-to-gcode", line 71
    print 'Tkinter are not installed! for linux use: "sudo apt-get install python-tk"'
                                                                                    ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('Tkinter are not installed! for linux use: "sudo apt-get install python-tk"')?

vs220

#
3 года, 6 месяцев назад

(отредактировано

3 года, 6 месяцев назад)

Темы:

22

Сообщения:

8090

Участник с: 16 августа 2009

А tk стоит?
Pacman -S tk

vasek

#
3 года, 6 месяцев назад

(отредактировано

3 года, 6 месяцев назад)

Темы:

47

Сообщения:

11417

Участник с: 17 февраля 2013

wau
File «/usr/sbin/image-to-gcode», line 71
print ‘Tkinter are not installed! for linux use: «sudo apt-get install python-tk»‘
SyntaxError: Missing parentheses in call to ‘print’. Did you mean print(‘Tkinter are not installed! for linux use: «sudo apt-get install python-tk»‘)?

Поставь кавычки скобки (описался) в line 71 — print(Tkinter are not installed! for linux use: «sudo apt-get install python-tk»)

PS — взял бы лучше с github ……… git clone https://github.com/robomechs/image-to-gcode.git и не нужно устанавливать …

Ошибки не исчезают с опытом — они просто умнеют

wau

#
3 года, 6 месяцев назад

Темы:

132

Сообщения:

978

Участник с: 11 октября 2013

Да, tk стоит.
Что видит Питон —



pip list
Package            Version
------------------ ----------------
anytree            2.6.0
appdirs            1.4.3
bsddb3             6.2.6
btrfsutil          1.1.1
CacheControl       0.12.5
chardet            3.0.4
chrome-gnome-shell 0.0.0
colorama           0.4.1
cupshelpers        1.0
cycler             0.10.0
distlib            0.2.9
distro             1.4.0
dxfwrite           1.2.1
fail2ban           0.10.4
gramps             5.0.1
html5lib           1.0.1
idna               2.8
isc                2.0
kiwisolver         1.1.0
lensfun            0.3.2
lockfile           0.12.2
louis              3.10.0
lxml               4.3.4
mallard-ducktype   1.0.1
matplotlib         3.1.1
msgpack            0.6.1
numpy              1.16.4
packaging          19.0
pep517             0.5.0
pilkit             2.0
Pillow             6.1.0
pip                19.0.3
pip-api            0.0.8
Pmw                2.0.1
progress           1.5
pwquality          1.4.0
pycairo            1.18.1
pycups             1.9.74
pycurl             7.43.0.3
Pygments           2.4.2
PyGObject          3.32.2
pyinotify          0.9.6
pyparsing          2.4.0
python-dateutil    2.8.0
pytoml             0.1.21
Reflector          2019.3.8.1.54.39
requests           2.22.0
retrying           1.3.3
setuptools         41.0.1
six                1.12.0
systemd-python     234
team               1.0
urllib3            1.25.3
webencodings       0.5.1

wau

#
3 года, 6 месяцев назад

Темы:

132

Сообщения:

978

Участник с: 11 октября 2013

Я и с Гита брал, и с cnc форума — сам модуль image-to-gcode требует модуль, на нем и падает.

vasek

#
3 года, 6 месяцев назад

Темы:

47

Сообщения:

11417

Участник с: 17 февраля 2013

wau
сам модуль image-to-gcode требует модуль, на нем и падает

Написано же явно — SyntaxError: Missing parentheses in call to ‘print’. Did you mean print …. (Отсутствуют скобки при вызове «print» ….)

Ошибки не исчезают с опытом — они просто умнеют

  • #1

Windows10
Python 3.9.6
tkinter, Pillow

Приветствую уважаемое сообщество.
Прошу помочь новичку преодолеть )
Не могу понять, как исправить ошибку, упорно возникающую при попытке открыть изображение не во внеших программах, а непосредственно в python.
Если вызываю изображение в браузер таким способом — окрывает:
import webbrowser
webbrowser.open(«D:PtRs.jpg»)

Если открываю то же изображение в gif через tkinter — работает:
from tkinter import *
root = Tk()
im = PhotoImage(file=’D:PtRs.gif’)
l = Label(root, image=im)
l.pack()
root.mainloop()

2021-08-19_190038.jpg

Таким способом тоже открывается в системном вьювере:
from PIL import Image
image = Image.open(‘D:\Pt\flowers-over-white-background.jpg’)
image.show()

А когда пытаюсь открыть jpg, png с использованием PIL в окне python — выдает ошибку:
Пример:
from PIL import Image
sample = Image.open(‘D:PtRs.jpg’)

2021-08-19_192628.jpg

Или вот , тоже ошибка:
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
# создаем рабочую область
frame = tkinter.Frame(root)
frame.grid()
#Добавим метку
label = tkinter.Label(frame, text=»Hello, World!»).grid(row=1,column=1)
# вставляем кнопку
but = tkinter.Button(frame, text=»Кнопка»).grid(row=1, column=2)
#Добавим изображение
canvas = tkinter.Canvas(root, height=400, width=700)
image = Image.open(«D:PtRs.jpg»)
photo = ImageTk.PhotoImage(image)
image = canvas.create_image(0, 0, anchor=’nw’,image=photo)
canvas.grid(row=2,column=1)
root.mainloop()
2021-08-19_193041.jpg

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • From keras models import sequential ошибка
  • From imageai detection import objectdetection ошибка