Related
I entered this code. I entered the example alike in the book where I could study Python.
from turtle import Screen, Turtle
import random
screen=Screen()
image1="C:\\rabbit.gif"
image2="C:\\turtle.gif"
screen.addshape(image1)
screen.addshape(image2)
t1=turtle.Turtle()
t1.shape(image1)
t1.pensize(5)
t1.penup()
t1.goto(-300, 0)
t2=turtle.Turtle()
t2.shape(image2)
t2.pensize(5)
t2.penup()
t2.goto(-300, -200)
t1.pendown()
t2.pendown()
t1.speed(1)
t2.speed(1)
for i in range(100):
d1=random.randint(1, 60)
t1.forward(d1)
d2=random.randint(1, 60)
t2.forward(d2)
I entered the code correctly, but there was an error.
Here is the code of the error.
Traceback (most recent call last):
File "D:/대학/파이썬프로그래밍기초/파이썬_과제(2018)/fd.py", line 7, in <module>
screen.addshape(image1)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1134, in register_shape
shape = Shape("image", self._image(name))
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 478, in _image
return TK.PhotoImage(file=filename, master=self.cv)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4093, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 4038, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "C:\rabbit.gif"
I tried to find a way to correct the error, but I couldn't find it. I wonder where this code is wrong.
I have been trying to make some graphs in pyqt5 that can update more quickly and efficiently than my currently embedded matplotlib ones.
I keep running into the same problem whenever I run any example code including pyqtgraph, which always throw the following error:
"TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget"
Environment:
Spyder 3.3.2 Python 3.7.1 64-bit | Qt 5.9.6 | PyQt5 5.9.2 | Windows 10.
After running pip freeze I learned my versions are numpy==1.20.1, PyQt5==5.15.2, PyQt5-sip==12.8.1, pyqtgraph==0.11.1
I'm using a very simple test graph from a turial (Link).
from PyQt5 import QtWidgets
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg
import sys # We need sys so that we can pass argv to QApplication
import os
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.graphWidget = pg.PlotWidget()
self.setCentralWidget(self.graphWidget)
hour = [1,2,3,4,5,6,7,8,9,10]
temperature = [30,32,34,32,33,31,29,32,35,45]
# plot data: x, y values
self.graphWidget.plot(hour, temperature)
def main():
app = QtWidgets.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The code which causes the error most recent in traceback is in "Qt.py", in the following code:
# Common to PyQt4 and 5
if QT_LIB in [PYQT4, PYQT5]:
QtVersion = QtCore.QT_VERSION_STR
try:
from PyQt5 import sip
except ImportError:
import sip
def isQObjectAlive(obj):
return not sip.isdeleted(obj)
loadUiType = uic.loadUiType
QtCore.Signal = QtCore.pyqtSignal
The full traceback is much longer, and is as follows:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not PlotItem
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 438, in resizeEvent
self.updateAutoRange()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 890, in updateAutoRange
childRange = self.childrenBounds(frac=fractionVisible)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 1355, in childrenBounds
px, py = [v.length() if v is not None else 0 for v in self.childGroup.pixelVectors()]
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 189, in pixelVectors
dt = self.deviceTransform()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 108, in deviceTransform
view = self.getViewWidget()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 65, in getViewWidget
if v is not None and not isQObjectAlive(v):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\Qt.py", line 328, in isQObjectAlive
return not sip.isdeleted(obj)
TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not PlotDataItem
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not PlotDataItem
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 26, in itemChange
self.parentChanged()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 463, in parentChanged
self._updateView()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 480, in _updateView
view = self.getViewBox()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 88, in getViewBox
vb = self.getViewWidget()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 65, in getViewWidget
if v is not None and not isQObjectAlive(v):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\Qt.py", line 328, in isQObjectAlive
return not sip.isdeleted(obj)
TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsObject.py", line 40, in itemChange
ret = sip.cast(ret, QtGui.QGraphicsItem)
TypeError: cast() argument 1 must be sip.simplewrapper, not ChildGroup
Traceback (most recent call last):
File "<ipython-input-2-5f5dea77ec5e>", line 1, in <module>
runfile('C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py', wdir='C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py", line 30, in <module>
main()
File "C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py", line 24, in main
main = MainWindow()
File "C:/Users/dowdt/GoogleDrive/Documents/Purdue/GraduateSchool/Homologation/Software/Python Test Code/Python GUI practice/pyqt5LiveGraphExample.py", line 19, in __init__
self.graphWidget.plot(hour, temperature)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\PlotItem\PlotItem.py", line 653, in plot
self.addItem(item, params=params)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\PlotItem\PlotItem.py", line 530, in addItem
self.vb.addItem(item, *args, **vbargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 409, in addItem
self.updateAutoRange()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 890, in updateAutoRange
childRange = self.childrenBounds(frac=fractionVisible)
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\ViewBox\ViewBox.py", line 1355, in childrenBounds
px, py = [v.length() if v is not None else 0 for v in self.childGroup.pixelVectors()]
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 189, in pixelVectors
dt = self.deviceTransform()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 108, in deviceTransform
view = self.getViewWidget()
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\graphicsItems\GraphicsItem.py", line 65, in getViewWidget
if v is not None and not isQObjectAlive(v):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyqtgraph\Qt.py", line 328, in isQObjectAlive
return not sip.isdeleted(obj)
TypeError: isdeleted() argument 1 must be sip.simplewrapper, not PlotWidget
I'm trying to write a program to take screen cap using a global hot key. Below is the corresponding code:
from datetime import datetime
import os
from pynput import keyboard
import pyautogui
import pathlib
def on_activate():
today = datetime.now()
d = today.strftime("%Y-%m-%d-%H-%M-%S")
myScreenshot = pyautogui.screenshot(region=(200,200, 1720, 800))
time_stamp = '{:%y%d%m}'.format(today)
fpath = pathlib.Path("C:","Users","Desktop","TestScreenCap", time_stamp)
if not os.path.exists(fpath):
os.makedirs(fpath)
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
Error Message:
Unhandled exception in listener callback
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save format = EXTENSION[ext]
KeyError: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
return f(self, *args, **kwargs)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process self.on_press(key)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
if f(*args) is False:
File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
return lambda k: f(l.canonical(k))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
self._on_activate()
File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
Traceback (most recent call last):
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2138, in save
format = EXTENSION[ext]
KeyError: ''
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/PycharmProjects/untitled1/123.py", line 26, in <module>
l.join()
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 259, in join
six.reraise(exc_type, exc_value, exc_traceback)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\six.py", line 702, in reraise
raise value.with_traceback(tb)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 211, in inner
return f(self, *args, **kwargs)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\_win32.py", line 280, in _process
self.on_press(key)
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\_util\__init__.py", line 127, in inner
if f(*args) is False:
File "C:/Users/PycharmProjects/untitled1/123.py", line 18, in <lambda>
return lambda k: f(l.canonical(k))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\pynput\keyboard\__init__.py", line 182, in press
self._on_activate()
File "C:/Users/PycharmProjects/untitled1/123.py", line 15, in on_activate
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
File "C:\Users\PycharmProjects\untitled1\venv\lib\site-packages\PIL\Image.py", line 2140, in save
raise ValueError("unknown file extension: {}".format(ext)) from e
ValueError: unknown file extension:
I do not know how to save the image to the folder. I expect the code below will not work this:
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
Changing the function to on_activate with a simple action such as:
Print("Hello")
The hotkey script works perfectly.
I am new to programming, so any help is appreciated!
Here the fixed code:
from datetime import datetime
import os
from pynput import keyboard
import pyautogui
import pathlib
def on_activate():
today = datetime.now()
d = today.strftime("%Y-%m-%d-%H-%M-%S")
myScreenshot = pyautogui.screenshot(region=(200,200, 1720, 800))
time_stamp = '{:%y%d%m}'.format(today)
fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp)
if not os.path.exists(fpath):
os.makedirs(fpath)
myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
def for_canonical(f):
return lambda k: f(l.canonical(k))
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<ctrl>+<alt>+h'),
on_activate)
with keyboard.Listener(
on_press=for_canonical(hotkey.press),
on_release=for_canonical(hotkey.release)) as l:
l.join()
The problem was that you were using:
myScreenshot.save(pathlib.Path(fpath,d,".jpg"))
The function pathlib.Path(fpath,d,".jpg") join the string adding the \ to the end of each, so the path where you are trying to save the file is:
C:Users\Desktop\TestScreenCap\200309\2020-09-03-16-50-20\.jpg
As you can see the filename is the extension, that throw the exception.
Just replace with this: myScreenshot.save(pathlib.Path(fpath,d + ".jpg"))
Another problem on the specified path is that C: is interpreted as Drive, so when you save the function, is saved to the path where your program is currently running, not at the real specified path. To fix this part, just replace C: with C:\\.
Reading your code I think you would like to save the screenshot in the current user Desktop, if so replace the line: fpath = pathlib.Path("C:\\","Users","Desktop","TestScreenCap", time_stamp) with fpath = pathlib.Path(os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop'), time_stamp) and just add on the top the import os. With this you don't need to care about the right generation for the path.
I have been trying to figure out what's wrong with this code:
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.widget import Widget
from kivy.clock import Clock
from plyer.facades import accelerometer
class Accel(Widget):
def __init__(self):
super().__init__()
self.sensorEnabled = False
def get_acceleration(self, dt):
val = accelerometer.acceleration
self.ids.label1.text = "X: " + str(val[0])
self.ids.label2.text = "Y: " + str(val[1])
self.ids.label3.text = "Z: " + str(val[2])
def pressed1(self):
try:
if not self.sensorEnabled:
# accelerometer.enable()
Clock.schedule_interval(self.get_acceleration, 1 / 20.)
self.sensorEnabled = True
self.ids.button1.text = "Stop"
else:
# accelerometer.disable()
Clock.unschedule(self.get_acceleration)
self.sensorEnabled = False
self.ids.button1.text = "Start"
except:
self.ids.status.text = "Accelerometer not supported"
class e3App(App):
def build(self):
return Accel()
if __name__ == '__main__':
e3App().run()
What happens is when I run it and press the START button it crashes and gives me this:
> Traceback (most recent call last): File
> "/usr/local/lib/python3.5/dist-packages/plyer/platforms/linux/accelerometer.py",
> line 22, in _get_acceleration
> pos = glob.glob("/sys/devices/platform/*/position")[0] IndexError: list index out of range During handling of the above
> exception, another exception occurred: Traceback (most recent call
> last): File
> "/home/rickdps/Desktop/KivyCookBook/InputMotionAndTouch/WorkingWithAccelerometer/main.py",
> line 42, in <module>
> e3App().run() File "/usr/local/lib/python3.5/dist-packages/kivy/app.py", line 828, in run
> runTouchApp() File "/usr/local/lib/python3.5/dist-packages/kivy/base.py", line 504, in
> runTouchApp
> EventLoop.window.mainloop() File "/usr/local/lib/python3.5/dist-packages/kivy/core/window/window_sdl2.py",
> line 663, in mainloop
> self._mainloop() File "/usr/local/lib/python3.5/dist-packages/kivy/core/window/window_sdl2.py",
> line 405, in _mainloop
> EventLoop.idle() File "/usr/local/lib/python3.5/dist-packages/kivy/base.py", line 339, in
> idle
> Clock.tick() File "/usr/local/lib/python3.5/dist-packages/kivy/clock.py", line 581, in
> tick
> self._process_events() File "kivy/_clock.pyx", line 367, in kivy._clock.CyClockBase._process_events
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:7700) File
> "kivy/_clock.pyx", line 397, in
> kivy._clock.CyClockBase._process_events
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:7577) File
> "kivy/_clock.pyx", line 395, in
> kivy._clock.CyClockBase._process_events
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:7498) File
> "kivy/_clock.pyx", line 167, in kivy._clock.ClockEvent.tick
> (/tmp/pip-build-rau3eo9p/kivy/kivy/_clock.c:3490) File
> "/home/rickdps/Desktop/KivyCookBook/InputMotionAndTouch/WorkingWithAccelerometer/main.py",
> line 15, in get_acceleration
> val = accelerometer.acceleration[:3] File "/usr/local/lib/python3.5/dist-packages/plyer/utils.py", line 103, in
> __getattribute__
> return getattr(object.__getattribute__(self, '_obj'), name) File
> "/usr/local/lib/python3.5/dist-packages/plyer/facades/accelerometer.py",
> line 44, in acceleration
> return self.get_acceleration() File "/usr/local/lib/python3.5/dist-packages/plyer/facades/accelerometer.py",
> line 60, in get_acceleration
> return self._get_acceleration() File "/usr/local/lib/python3.5/dist-packages/plyer/platforms/linux/accelerometer.py",
> line 24, in _get_acceleration
> raise Exception('Could not enable accelerometer!') Exception: Could not enable accelerometer!
I am following this book called "Kivy Cook Book", and I've mostly copied and pasted code in order to try it. This one has not worked though.
I'd really appreciate any help.
When I do general PIL commands in Python, I get such an error message:
>>> im.save('layer_86_.tiff')
TIFFSetField: layer_86_.tiff: Unknown tag 33922.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1685, in save
save_handler(self, fp, filename)
File "C:\Python34\lib\site-packages\PIL\TiffImagePlugin.py", line 1185, in _save
e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 430, in _getencoder
return encoder(mode, *args + extra)
RuntimeError: Error setting from dictionary
I've seen at Github and SO similar questions, that date back to many years ago. But in my case this problem still can be reproduced. I've even installed libtiff.dll and put it in the System32 and SysWOW64 folders, but to no avail. So, how can I fix it?
This is another error message, that I see, when I try to rotate an image:
>>> from PIL import Image
>>> Image.MAX_IMAGE_PIXELS = 100000000000
>>> img = Image.open('layer_71_.tiff')
>>> img.rotate(80,expand=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1603, in rotate
return self.transform((w, h), AFFINE, matrix, resample)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1862, in transform
im.__transformer((0, 0)+size, self, method, data, resample, fill)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1910, in __transformer
image.load()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 245, in load
if not self.map and (not LOAD_TRUNCATED_IMAGES or t == 0) and e < 0:
TypeError: unorderable types: tuple() < int()
So it seems like PIL does not work in many cases.