ImportError: cannot import name 'itemgetter' from 'operator' - python-3.x

Help me with my problem, I've made some file that named 'percobaan.py' and I ran it with cmd and it's got some error. the error say ImportError: cannot import name 'itemgetter' from 'operator', But if I run my code in python IDLE the code runs without any errors.
My code:
import tkinter
def msg():
print("i'm learning tkinter built in")
root = tkinter.Tk()
label = tkinter.Label(root, text='welcome to the tkinter built in project')
label.pack()
label2 = tkinter.Label(root,text='choose your favorite programming languange',
justify=tkinter.CENTER,
padx=20)
label2.pack()
tkinter.Radiobutton(root, text='python',padx=20, value= 1).pack(anchor=tkinter.N)
tkinter.Radiobutton(root, text='Javascript',padx=20, value= 2).pack(anchor=tkinter.N)
tkinter.Radiobutton(root, text='C++',padx=20, value= 3).pack(anchor=tkinter.N)
tkinter.Radiobutton(root, text='C',padx=20, value= 4).pack(anchor=tkinter.N)
frame = tkinter.Frame(root)
frame.pack()
button = tkinter.Button(frame, text='quit',fg='black',command=quit)
button.pack(side=tkinter.LEFT)
slogan = tkinter.Button(frame, text='see the message',command=msg)
slogan.pack(side=tkinter.RIGHT)
root.mainloop()
and the error says:
Traceback (most recent call last):
File "GUI.py", line 1, in <module>
import tkinter
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 39, in <module>
import re
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\re.py", line 125, in <module>
import functools
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\functools.py", line 21, in <module>
from collections import namedtuple
File "C:\Users\khairunnisa\AppData\Local\Programs\Python\Python37-32\lib\collections\__init__.py", line 21, in <module>
from operator import itemgetter as _itemgetter, eq as _eq
ImportError: cannot import name 'itemgetter' from 'operator' (D:\JOB\__python\exercise_oop\GUI\operator.py)
I've tried many times to run this code and the packages are already installed on my PC, but the result is still nothing.
any idea why?

Related

How to get rid of this problem in openCV tkinter code

I am working on a facial recognition based attendance system .This is my first project so i am not well acquainted with how to deal with errors. I am stuck in the middle and don't know how to solve the error. My terminal displays the following error:
PS E:\Project Work> & "C:/Users/Naik Faheem/AppData/Local/Programs/
Python/Python39/python.exe" "e:/Project Work/test.py"
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Naik Faheem\AppData\Local\Programs\Python\
Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "e:\Project Work\test.py", line 62, in face_recog
img=recognize(img,clf,facecascade)
File "e:\Project Work\test.py", line 52, in recognize
coord= draw_boundary(img,facecascade,1.1,10,255,"Face",clf)
File "e:\Project Work\test.py", line 39, in draw_boundary
n="+".join(n)
TypeError: can only join an iterable
[ WARN:1] global C:\Users\runneradmin\AppD
I HAVE PUT MY ACTUAL CODE BELOW.This code is intended to read classifier.xml file that stores the trained dataset.
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import messagebox
import mysql.connector
import cv2
class Face_recognition:
def __init__(self,root):
self.root=root
self.root.title('Face Detection')
self.root.geometry('1500x800+0+0')
self.root.config(bg='gray')
title_lbl=Label(self.root,text='FACE RECOGNITION',
font=('times new roman',35,'bold'),bg='gray',fg='darkblue')
title_lbl.place(x=0,y=0,width=1500,height=40)
btn=Button(self.root,command=self.face_recog,text='Detect Face',
font=('times new roman',12,'bold'),bg='red')
btn.place(x=650,y=60,width=200,height=40)
def face_recog(self):
def draw_boundary(img,classifier,scaleFactor,minNeighbors,color,text,clf):
gray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
features = classifier.detectMultiScale(gray_image,scaleFactor,minNeighbors)
coord= []
for (x,y,w,h) in features:
cv2.rectangle(img,(x,y),(x+w,y+h),255,3)
id,predict= clf.predict(gray_image[y:y+h,x:x+w])
confidence= int(100*(1-predict/300))
con= mysql.connector.connect( user='root', host='localhost',
password='',database='stu_details')
cur=con.cursor()
cur.execute("select name from stu_info where name= "+str(id-1))
n=cur.fetchone()
n="+".join(n)
if confidence>70:
cv2.putText(img,f"Name: {n}",(x,y-60),cv2.FONT_HERSHEY_COMPLEX,1,255,2)
else:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,255),4)
cv2.putText(img,"Unknown face",(x,y10),
cv2.FONT_HERSHEY_COMPLEX_SMALL,0.8,(255,255,255),3)
coord=[x,y,w,h]
return coord
def recognize(img,clf,facecascade):
coord= draw_boundary(img,facecascade,1.1,10,255,"Face",clf)
return img
facecascade= cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
clf= cv2.face.LBPHFaceRecognizer_create()
clf.read("classifier.xml")
video_cap=cv2.VideoCapture(0)
while True:
ret,img=video_cap.read()
img=recognize(img,clf,facecascade)
cv2.imshow("Welcome to face recognition",img)
if cv2.waitKey(1)==13:
break
video_cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
root=Tk()
app=Face_recognition(root)
root.mainloop()
Error fixed:
Register the records in an ascending id (e.g 1,2,3....)and this problem gets solved
Change your data type from int to varchar in your data base
to get rid of this error.

pycharm project works on 'run' but pyinstaller --onefile gives errors related to pulp

I've been working on a project where a user can upload a file for analysis via pulp. When I run the project in pycharm it works fine, but after I build a --onefile with pyinstaller... I get the following traceback
Exception in Tkinter callback
Traceback (most recent call last):
File "tkinter\__init__.py", line 1702, in __call__
File "example.py", line 29, in get_file
File "pydfs_lineup_optimizer\lineup_optimizer.py", line 351, in optimize
File "pydfs_lineup_optimizer\solvers\pulp_solver.py", line 39, in solve
File "site-packages\pulp\pulp.py", line 1664, in solve
AttributeError: 'NoneType' object has no attribute 'actualSolve'
Here is a piece of the code I'm having an issue with:
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
import csv
import time
import os, sys
import PIL
from PIL import Image, ImageTk
from tkinter.font import Font
def get_file():
global file
file = tk.filedialog.askopenfilename()
def run_it():
from pydfs_lineup_optimizer import Site, Sport, get_optimizer
optimizer = get_optimizer(Site.FANDUEL, Sport.BASEBALL)
optimizer.load_players_from_CSV(file)
lineup_generator = optimizer.optimize(3)
with open('Lineup.csv', "w") as csv_file:
writer = csv.writer(csv_file, delimiter=' ')
for lineup in lineup_generator:
writer.writerow([lineup])
top = tk.Tk()
top.geometry("600x337")
if getattr(sys, 'frozen', False):
baseDir = sys._MEIPASS
else:
baseDir = os.path.abspath(os.path.dirname(__file__))
image = Image.open(os.path.join(baseDir, 'baseball.jpg'))
photo = ImageTk.PhotoImage(image)
L0 = Label(top, image=photo)
L2 = Button(top, text="UPLOAD", fg="blue", font=font2, command=get_file).grid(row=1, column=4)
L3 = Button(top, text="RUN", fg="blue", font=font2, command=run_it).grid(row=2, column=4)
top.mainloop()
Pulp requires the cbc.exe file to be available to use to actually solve the lp problems.
Unfortunately pyinstaller doesn't pick that up by default and you need to figure out a way to package the cbc.ex file then tell the COIN_CMD() solver where to find it.
Do this by using COIN_CMD(path=<your_path_here>)

AttributeError: module 'typing' has no attribute 're' in pandas Python 3.7

I can't import pd from pandas because i have this error. I search on google but I didn't find the fix for this..
>>> import pandas
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python37\lib\site-packages\pandas\__init__.py", line 23, in <module>
from pandas.compat.numpy import *
File "C:\Python37\lib\site-packages\pandas\compat\__init__.py", line 431, in <module>
re_type = typing.re.Pattern
AttributeError: module 'typing' has no attribute 're'
I think this is changing underneath us as Python's typing module matures, but in our case, the issue was that we did from Typing import re, and then later did something like:
def funct(some_re: re.Pattern):
The fix was dumb. Simply change your import to be from typing import Pattern and then do:
def funct(some_re: Pattern):
Bleh. Warts.

Python's exec running in module works but in function not

This works:
import os
import sys
with open('tests.py') as fptr:
script_content = fptr.read()
exec(script_content)
And this not:
def run():
import os
import sys
with open('tests.py') as fptr:
script_content = fptr.read()
exec(script_content)
run()
Result:
Traceback (most recent call last):
File "tmp.py", line 8, in <module>
run()
File "tmp.py", line 6, in run
exec(script_content)
File "<string>", line 15, in <module>
File "<string>", line 16, in PlaceSpitter
NameError: name 'Place' is not defined
Could anyone tell my why and how to fix it?
I've read again - carrefully - python's docs especially this one:
Remember that at module level, globals and locals are the same dictionary
And try this:
def run():
import os
import sys
with open('tests.py') as fptr:
script_content = fptr.read()
exec(script_content, globals())
run()
which now works!
I still don't know why but now at least it works.

For py2exe, is there a way to choose the save location of the executable?

I know there's already a question like this, but I got this error when I used it:
Traceback (most recent call last):
File "C:/Users/rperera/PycharmProjects/PythonToExe/test.py", line 12, in <module>
save_path = filedialog.asksaveasfilename(defaultextension="*.exe", filetypes=("Executable File", "*.exe"))
File "C:\Python34\lib\tkinter\filedialog.py", line 380, in asksaveasfilename
return SaveAs(**options).show()
File "C:\Python34\lib\tkinter\commondialog.py", line 48, in show
s = w.tk.call(self.command, *w._options(self.options))
_tkinter.TclError: bad file type "*.exe", should be "typeName {extension ?extensions ...?} ?{macType ?macTypes ...?}?"
Can anyone help me on how to fix this? Here's my code:
from distutils.core import setup
import py2exe, sys
import tkinter as tk
from tkinter import filedialog
input('Press Enter to continue and select your Python file you want to convert when the dialog shows up...')
tk.Tk().withdraw()
file_path = tk.filedialog.askopenfilename()
sys.argv.append("py2exe")
input("Press Enter to continue and choose where you want to save the new executable file when the dialog shows up...")
save_path = filedialog.asksaveasfilename(defaultextension="*.exe", filetypes=("Executable File", "*.exe"))
setup(console=[file_path], options={'py2exe': {'compressed': 1, 'bundle_files': 1, 'dist_dir': save_path + "dir"}})

Resources