From pil import image imagetk ошибка

I cannot seem to figure out how to fix a problem with my code regarding import ImageTK from PIL. I have searched and downloaded Pillow different ways and the error of the code is still the same.

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'

These are the import codes of the file

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

and this is the code that is trying to import the image

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)

How may I fix this problem?

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

@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()

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

  • [Solved] typeerror: unsupported format string passed to list.__format__

    [Solved] typeerror: unsupported format string passed to list.__format__

    May 31, 2023

  • Solving ‘Remote End Closed Connection’ in Python!

    Solving ‘Remote End Closed Connection’ in Python!

    by Namrata GulatiMay 31, 2023

  • [Fixed] io.unsupportedoperation: not Writable in Python

    [Fixed] io.unsupportedoperation: not Writable in Python

    by Namrata GulatiMay 31, 2023

  • [Fixing] Invalid ISOformat Strings in Python!

    [Fixing] Invalid ISOformat Strings in Python!

    by Namrata GulatiMay 31, 2023

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Понравилась статья? Поделить с друзьями:
  • From flask import flask ошибка
  • Fprnm1c dll фискальный регистратор ошибка при подключении
  • Fprint 5200 ошибки в фп
  • Foxmail ошибка соединения ssl errorcode 5
  • From dust вылетает с ошибкой