我有一个应该截取屏幕的程序......
#imports pyqt
from PyQt4.QtGui import QPixmap, QApplication
#declares variables
date = datetime.datetime.now()
counter = 0
#sets directory to be used to save screenshots
directorydate = str(date.year) + str(date.month) + str(date.day) + str(date.hour) +str(date.minute) + str(date.second)
directory = os.path.abspath('Photos%s' % directorydate)
#some weird PyQt thing I don't understand
app = QApplication(sys.argv)
#game loop
while True
counter += 1
#declarations
picdate = str(date.year) + str(date.month) + str(date.day) + str(date.hour) +str(date.minute) + str(date.second) + str(counter) + '.png'
pic = QPixmap.grabWindow(QApplication.desktop().winId())
#saves screenshots to a custom directory
pic.save('Photos%s/' % directorydate + picdate)
#adds screenshots to list and deletes them once 150 have been collected
if counter == 1:
pics = [picdate]
picfirst = pics[0]
if not os.path.exists(directory):
os.makedirs(directory)
else:
pics.append(picdate)
if counter == 150:
os.remove(picfirst)
pics.remove(picfirst)
counter = 0
...然后将它们设置为pygame窗口
background = pygame.image.load('Photos%s/' % directorydate + picdate)
displaysurf.blit(background)
#pygame event handling
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
当我尝试运行它时,shell会给我"错误:无法打开照片_____ / ____。png
我不确定问题是什么,无论PyGame和PyQt之间的兼容性如何,一旦图像保存为.png,它应该能够像任何其他图像一样加载。是因为它在代码运行时已经打开了吗?
任何解释和/或解决方案都将不胜感激,谢谢。
答案 0 :(得分:0)
问题是你首先使用counter = 1保存pic,而不检查目录是否存在,因此根本不保存。 之后,如果pic计数器== 1,则创建目录,因此创建目录并且所有其他图片将保存在其中但不是第一个。 当您尝试打开不在目录中的第一张照片时会出现错误,因为由于目录不存在而未保存。 解决方案是移动此代码:
if not os.path.exists(directory):
os.makedirs(directory)
这里:
#sets directory to be used to save screenshots
directorydate = str(date.year) + str(date.month) + str(date.day) + str(date.hour) +str(date.minute) + str(date.second)
directory = os.path.abspath('Photos%s' % directorydate)
if not os.path.exists(directory):
os.makedirs(directory)