How to blit a PyQt screenshot to PyGame Window - python

I have a program that is supposed to take screenshots...
#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
...then animates them to the pygame window
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()
When I try to run it, the shell gives me "error: Couldn't open Photos_____/____.png
I am not sure what the problem is as regardless of compatibility between PyGame and PyQt, once the image is saved as a .png, it should be able to be loaded like any other image. Is it just because it's open already while the code is running?
Any explanations and/or solutions would be appreciated, thank you.

Problem is that you first save pic with counter=1 without checking if directory exists so it's not saved at all.
After that you create directory if the pic counter == 1, so directory is created and all other pics will be saved in it but not first one.
You get error when you try to open that first pic which is not in the directory since it was not saved because directory has not existed.
Solution is to move this code:
if not os.path.exists(directory):
os.makedirs(directory)
here:
#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)

Related

Change Wallpapaer windows in different Screen , with python

I want to put different wallpaper on different Display(Monitor).
I'm starting a little project to change the windows wallpaper a little easier and with more features, but it doesn't work properly with two monitors. It changes the wallpaper of the two Monitors.
I didn't find any way to solve the problem with this method of changing the wallpaper. I wonder if there is any way
import os, ctypes
import tempfile , time
path = os.path.expanduser("~\Pictures")
count = 0
extAcept = [".jpg", ".png", ".bmp", ".jpge"]
def mudaImage(path):
pathT = path
SPI_SETDESKWALLPAPER = 20
for file in os.listdir(pathT):
tempN = 0
for ext in extAcept:
if file.endswith(ext):
way = pathT+"\\"+file
neway = my_replace(way,"\\","/")
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, neway, 0x3)
tempN += 1
#print(neway)
time.sleep(2)
count = tempN
if count == 0:
print("Nenhum arquivo foi encontrado")
def my_replace(arg1,chrt1,chrt2):
caminho = arg1.replace(chrt1,chrt2)
return caminho
mudaImage(pasta)

Using Image.show() fails because the temporary file written does not exist (Windows 10, Pillow 9.0.1)

I have seen this post for Ubuntu 20.04 and Pillow version 9.0.0 but the problem now exists on my Windows machine running Python 3.9.12 locally. What is weird is that it has worked fine the last two weeks and decided today to delete a temporary photo immediately after displaying it to me and therefore blocking me from seeing it.
My code is as follows though I believe it does not matter
if file[file.index('.')+1:] == "jpg" or file[file.index('.')+1:] == "png": #only jpg and png files
totalImages += 1
img = Image.open(str(pathArg2) + '/' + file) #opens the image
exif_date = img.getexif().get(306) #gets the date from the exif data
if exif_date != None:
for coord in locations:
for time in coord.time:
if exif_date[0:15] == time[0:15]: #if the creation time of the image up to a 10 minute interval is the same as the time of the location
address = locator.reverse(coord.coords).address #gets the address of the location
image_editable = ImageDraw.Draw(img)
image_editable.text((15,15), address, fill = (170, 255, 0), font = ImageFont.truetype("arial.ttf", int((img.width*img.height) ** (1./4.)))) #adds the address text to the image
img.show()
print("Was the address correct? (y/n)")
answer = input("> ")
while answer != "y" and answer != "n": #checks if the address is correct with the user
answer = input("> ")
if answer == "y":
imagesCorrectlyAnnotated += 1
img.close()
return True
else:
imagesIncorrectlyAnnotated += 1
img.close()
img = Image.open(str(pathArg2) + '/' + file)
imagesAnnotated += 1
time.sleep() does not do anything either but that is what I thought would be the case
Commenting out code below img.show() does not change the behavior.
If I run even a simple python program to show an image such as
from PIL import Image
import time
img = Image.open('TestImages/20211203_175356.jpg')
img.show()
time.sleep(30)
It still shows and then immediately removes the images and says its been deleted, even if the program is still running

PyGame Invalid Position For Blit

I am creating a small level designer in Python (using PyGame).
The program is supposed to just let you place down an image, change between images, export to a PNG file, and export image path and coordinates to where it was place in a text document. I have gotten all of these components to work, but I am stuck with one last component, and that is reading the text document back into PyGame, and re-placing all of the images in the correct places with the correct sprites.
The way that I have it currently (Which has been rewritten and Almost works) produces an error whenever I try to read from one of my exported files.
The error of course is:
stamped_surface.blit(image, (xcrds, ycrds))
TypeError: invalid destination position for blit
Here is my code:
import pygame as pg
import threading
import time
import pygame
from random import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfile
image_file = "../res/ExampleProject/TankGame/TankGameImg/tileGrass_transitionE.png"
f = open("../Saves/Backups/FailSafe.txt", "a+")
f.write("""
#################################################
# PyEngine #
# FailSafe #
# File #
# By MouseBatteries #
#################################################
""")
pg.init()
xcrds = 17
ycrds = 13
black = (0,0,0)
sw = 1280
sh = 720
screen = pg.display.set_mode((sw, sh))
pg.display.set_caption('thing')
image = pg.image.load(image_file).convert()
start_rect = image.get_rect()
image_rect = start_rect
running = True
stamped_surface = pg.Surface((sw, sh))
while running:
event = pg.event.poll()
keyinput = pg.key.get_pressed()
# Escape Program
if keyinput[pg.K_ESCAPE]:
fname = "../Saves/Design_complete.png"
pg.image.save(stamped_surface, fname)
print("File saved at {} ".format(fname))
quit()
#Save Work In Project File
if keyinput[pg.K_s]:
fname = "../Saves/LevelSave.png"
pg.image.save(stamped_surface, fname)
print("File saved at {} ".format(fname))
#Open New Selectable
if keyinput[pg.K_n]:
image_file = askopenfilename()
image = pg.image.load(image_file).convert()
print("Placable Updated!")
if keyinput[pg.K_e]:
fname = "../Saves/Export.png"
pg.image.save(stamped_surface, fname)
print("File saved at {} ".format(fname))
pg.quit()
#Recreate Terrain From File
if keyinput[pg.K_o]:
fileDest = askopenfilename()
openFile = open(fileDest, "r")
for line in openFile:
li = line.strip()
if li.startswith("Pec:"): #pec stands for "PyEngineCoords"
reimgpath = (line.rstrip())
nopecimgpath = reimgpath.replace("Pec:", "")
print(nopecimgpath)
image = pg.image.load(nopecimgpath).convert()
pg.display.update()
if li.startswith("Crdsx:"):
xposcrds = (line.rstrip())
xcrds = xposcrds.replace("Crdsx:", "")
x = int(xcrds)
print(x)
pg.display.update()
if li.startswith("Crdsy:"):
yposcrds = (line.rstrip())
ycrds = yposcrds.replace("Crdsy:", "")
y = int(ycrds)
print(y)
pg.display.update()
stamped_surface.blit(image, (xcrds, ycrds))
elif event.type == pg.QUIT:
running = False
elif event.type == pg.MOUSEMOTION:
image_rect = start_rect.move(event.pos)
elif event.type == pg.MOUSEBUTTONDOWN:
stamped_surface.blit(image, event.pos)
print("Image Placed!")
print(image_file, event.pos)
f.write("\nPec:" + image_file + "\nCrdsx:")
print(event.pos)
xpos_str = str(pg.mouse.get_pos()[0])
ypos_str = str(pg.mouse.get_pos()[1])
f.write(xpos_str)
f.write("\nCrdsy:")
f.write(ypos_str)
f.flush()
screen.fill(black)
screen.blit(stamped_surface, (0, 0))
screen.blit(image, image_rect)
pg.display.flip()
This program has a file system and certain controls to make things happen, so here they are:
ESC KEY - Auto Exports Program For Reference And Quits Program
S Key - Saves Surface as PNG file.
N Key - Prompts User to select new sprite to use
E Key - Exports Image To PNG with file prompt
O Key - Opens File With Coordinate data and image path data.
Image Of Root File System:
https://i.imgur.com/KouhmjK.png
A Few things you should know:
This program auto-saves every file position to the file that contains Coords and Image Paths.
The file system is relatively simple to work out by looking at the code, but if you need some assistance, please ask.
blits((source, dest, area), ...)) -> (Rect, ...) you are missing out the destination. Read here
And if you are making use of coordinates then use square brackets [x-co,y-co]
like this:
block.blit(image,[0,0])

Screenshot script can't save the .png image with the actual date

I'm writing a python script to screenshot every 30 seconds and save the output image with the actual date.
The problem is that the script is saving each image with each letter of the time.ctime() output (Tue Jan 3 01:30:53 2017):
T.png
u.png
e.png
...
How can i save each image output with the actual complete date ?
import pyscreenshot as ImageGrab
import time
max_prints = 10
counter = 0
timer = time.ctime()
while counter < max_prints:
for mark in timer:
im=ImageGrab.grab()
#im.show()
im=ImageGrab.grab(bbox=(10,10,500,500))
#im.show()
ImageGrab.grab_to_file(str(mark) + ".png")
time.sleep(30)
This loop may help:
while counter < max_prints:
im = ImageGrab.grab(bbox=(10, 10, 500, 500))
filename = str(dt.datetime.now()).replace(' ', 'T').split('.')[0] + ".png"
ImageGrab.grab_to_file(filename)
time.sleep(5)
Can you try with something like thisĀ ?
import pyscreenshot as ImageGrab
import time
max_prints = 10
counter = 0
while counter < max_prints:
im=ImageGrab.grab()
#im.show()
im=ImageGrab.grab(bbox=(10,10,500,500))
#im.show()
timer = time.ctime()
ImageGrab.grab_to_file(timer + ".png")
time.sleep(30)
counter += 1
If you want to you could have filenames that will be easier to handle afterward by changing these lines:
timer = time.ctime()
ImageGrab.grab_to_file(timer + ".png")
To this:
timer = time.ctime()
timestamp = timer.replace(' ', '_')
timestamp = timestamp.replace(':', '_')
filename = "{}.png".format(timestamp)
ImageGrab.grab_to_file(filename)
But it depends on how you want your files to be named.

CX_Freeze for my python script -- Fix up module error?

This is my main code:
import turtle
import random
from sys import exit
import canvasvg
import os
import tempfile
import shutil
import cairosvg
red = 125
green = 70
blue = 38
pen = 15
def runChk():
runAgain = input("Would you like to return to menu? Y/N (N will exit) \n")
if runAgain.upper() == "Y":
print("Running...")
turtle.clearscreen()
start()
elif runAgain.upper() == "N":
print("Exiting...")
exit()
else:
print("Invalid response.")
runChk()
def saveImg():
print("Done.")
save = input("Would you like to save this tree? Y/N \n")
if save.upper() == "Y":
filename = input("What would you like to name it? \n")
print("Ignore following warning...")
if not filename.lower().endswith('.png'):
filename += '.png'
target_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'Images', filename)
tmpdir = tempfile.mkdtemp() # create a temporary directory
tmpfile = os.path.join(tmpdir, 'tmp.svg') # name of file to save SVG to
ts = turtle.getscreen().getcanvas()
canvasvg.saveall(tmpfile, ts)
with open(tmpfile) as svg_input, open(target_path, 'wb') as png_output:
cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
shutil.rmtree(tmpdir) # clean up temp file(s)
print("Saved!")
runChk()
elif save.upper() == "N":
runChk()
else:
print("Invalid response. \n")
saveImg()
def tree(branchLen, red, green, blue, pen):
if branchLen > 3:
pen = pen*0.8
turtle.pensize(pen)
if (red > 10 and green < 140):
red = red - 15
green = green + 8
if branchLen > 5:
angle = random.randrange(18, 55)
angleTwo = 0.5*angle
sub = (0.8*(random.randrange(1,20)))
print("Angle 1: ", angle, "Angle 2: ", angleTwo, " Branch length subtracted by ", sub)
turtle.color(red, green, blue)
turtle.forward(branchLen)
turtle.right(angleTwo)
tree(branchLen-sub, red, green, blue, pen)
turtle.left(angle)
tree(branchLen-sub, red, green, blue, pen)
turtle.right(angleTwo)
turtle.backward(branchLen)
def main():
turtle.colormode(255)
turtle.bgcolor(102, 255, 255)
turtle.left(90)
turtle.up()
turtle.speed(0)
turtle.hideturtle()
turtle.backward(440)
turtle.down()
print("Please wait while I draw...")
tree(random.randrange(80, 95),red,green,blue, pen)
turtle.update()
saveImg()
def start():
live = 1
print("What would you like to do?\n")
usr = input("Type 'run' to start a fractal. \nType 'run static' to create a fractal without live drawing (faster). \nOr 'exit' to exit. \n")
if usr.upper() == "RUN":
live = 1
print("Running...")
main()
elif usr.upper() == "RUN STATIC":
live = 0
print("Running...")
turtle.tracer(0)
main()
elif usr.upper() == "EXIT":
print("Exiting...")
exit()
else:
print("Invalid response.")
start()
start()
it is called fractal.py. I copied that and canvasvg to the main python folder. I created a cx_freeze setup as so:
from cx_Freeze import setup, Executable
# NOTE: you can include any other necessary external imports here aswell
includefiles = [] # include any files here that you wish
includes = []
excludes = []
packages = ['turtle', 'random', 'sys', 'canvasvg', 'os', 'tempfile', 'shutil', 'cairosvg']
exe = Executable(
# what to build
script = "fractal.py", # the name of your main python script goes here
initScript = None,
base = None, # if creating a GUI instead of a console app, type "Win32GUI"
targetName = "Fractal Tree.exe", # this is the name of the executable file
copyDependentFiles = True,
compress = True,
appendScriptToExe = True,
appendScriptToLibrary = True,
icon = None # if you want to use an icon file, specify the file name here
)
setup(
# the actual setup & the definition of other misc. info
name = "Fractal Tree", # program name
version = "0.4.2",
description = 'Creates a fractal tree',
author = "TomSoft Programs",
options = {"build_exe": {"excludes":excludes,"packages":packages,
"include_files":includefiles}},
executables = [exe]
)
When I run cmd as python setup.py build, I get no errors. I go to the build folder and find my fractal.exe program. It closes very quickly and I can't get the full error (because of the speedy closing) but I know it says something like:
ReferenceError: 'module' object has no attribute '_fix_up_module'
What can I do to fix this? I'm very new to python and cx_freeze, so I'm sure I'm doing something wrong in setup.py.
For anyone who finds this, it's a bug with cx_freeze. You've done nothing wrong. Download cx_freeze from here, the bug is fixed at this download location.

Categories

Resources