/
Visor.py
371 lines (289 loc) · 15.4 KB
/
Visor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# Versión Python: 3.6.0
# Versión PyQt5: 5.11.3
import shutil
import os
from random import randint
import random
from PyQt5.QtGui import QIcon, QFont, QPalette, QImage, QPixmap
from PyQt5.QtCore import (Qt, QDir, QFile, QFileInfo, QPropertyAnimation, QRect, QAbstractAnimation, QTranslator, QLocale, QLibraryInfo)
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton, QMessageBox, QFrame, QLabel, QFileDialog)
global Contador
# ========================= CLASE Widgets ==========================
class Widgets(QWidget):
def __init__(self, parent=None):
super(Widgets, self).__init__(parent)
self.parent = parent
self.initUI()
def initUI(self):
# ======================== WIDGETS ===========================
framePrincipal = QFrame(self)
framePrincipal.setFrameShape(QFrame.Box)
framePrincipal.setFrameShadow(QFrame.Sunken)
framePrincipal.setAutoFillBackground(True)
framePrincipal.setBackgroundRole(QPalette.Light)
framePrincipal.setFixedSize(640,480)
framePrincipal.move(10, 10)
frame = QFrame(framePrincipal)
frame.setFixedSize(2000, 2000)
frame.move(10, 10)
self.labelImagen = QLabel(frame)
self.labelImagen.setAlignment(Qt.AlignCenter)
self.labelImagen.setGeometry(0, 0, 640, 480)
self.labelImagenUno = QLabel(frame)
self.labelImagenUno.setAlignment(Qt.AlignCenter)
self.labelImagenUno.setGeometry(-650, 0, 640, 480)
# =================== BOTONES (QPUSHBUTTON) ==================
self.buttonCargar = QPushButton("Cargar imagen", self)
self.buttonCargar.setCursor(Qt.PointingHandCursor)
self.buttonCargar.setFixedSize(100, 30)
self.buttonCargar.move(10, 519)
self.buttonEliminar = QPushButton("Eliminar imagen", self)
self.buttonEliminar.setCursor(Qt.PointingHandCursor)
self.buttonEliminar.setFixedSize(100, 30)
self.buttonEliminar.move(120, 519)
self.buttonAnterior = QPushButton("<", self)
self.buttonAnterior.setObjectName("Anterior")
self.buttonAnterior.setToolTip("Imagen anterior")
self.buttonAnterior.setCursor(Qt.PointingHandCursor)
self.buttonAnterior.setFixedSize(30, 30)
self.buttonAnterior.move(230, 519)
self.buttonSiguiente = QPushButton(">", self)
self.buttonSiguiente.setObjectName("Siguiente")
self.buttonSiguiente.setToolTip("Imagen siguiente")
self.buttonSiguiente.setCursor(Qt.PointingHandCursor)
self.buttonSiguiente.setFixedSize(30, 30)
self.buttonSiguiente.move(265, 519)
self.buttonCarpeta1= QPushButton("Carpeta 1", self)
self.buttonCarpeta1.setObjectName("Carpeta1")
self.buttonCarpeta1.setToolTip("Guardar en Carpeta 1")
self.buttonCarpeta1.setCursor(Qt.PointingHandCursor)
self.buttonCarpeta1.setFixedSize(160,30)
self.buttonCarpeta1.move(300,519)
self.buttonCarpeta2= QPushButton("Carpeta 2", self)
self.buttonCarpeta2.setObjectName("Carpeta2")
self.buttonCarpeta2.setToolTip("Guardar en Carpeta 2")
self.buttonCarpeta2.setCursor(Qt.PointingHandCursor)
self.buttonCarpeta2.setFixedSize(160,30)
self.buttonCarpeta2.move(465,519)
# ===================== CONECTAR SEÑALES =====================
self.buttonCargar.clicked.connect(self.Cargar)
self.buttonEliminar.clicked.connect(self.Eliminar)
self.buttonAnterior.clicked.connect(self.anteriorSiguiente)
self.buttonSiguiente.clicked.connect(self.anteriorSiguiente)
self.buttonCarpeta1.clicked.connect(self.GuardarCarpeta1)
self.buttonCarpeta2.clicked.connect(self.GuardarCarpeta2)
# Establecer los valores predeterminados
self.posicion = int
self.estadoAnterior, self.estadoSiguiente = False, False
self.carpetaActual = QDir()
self.imagenesCarpeta = []
# ======================= FUNCIONES ==============================
def bloquearBotones(self, bool):
self.buttonCargar.setEnabled(bool)
self.buttonEliminar.setEnabled(bool)
self.buttonAnterior.setEnabled(bool)
self.buttonSiguiente.setEnabled(bool)
self.buttonCarpeta1.setEnabled(bool)
self.buttonCarpeta2.setEnabled(bool)
def Mostrar (self, label, imagen, nombre, posicionX=650):
imagen = QPixmap.fromImage(imagen)
# Escalar imagen a 640x480 si el ancho es mayor a 640 o el alto mayor a 480
if imagen.width() > 640 or imagen.height() > 480:
imagen = imagen.scaled(640, 480, Qt.KeepAspectRatio, Qt.SmoothTransformation)
if imagen.width() < 640 or imagen.height() < 480:
imagen = imagen.scaled(640, 480, Qt.KeepAspectRatio, Qt.SmoothTransformation)
# Mostrar imagen
label.setPixmap(imagen)
# Animación (al finalizar la animación se muestra en la barra de estado el nombre y la extensión de la imagen
# y se desbloquean los botones).
self.animacionMostar = QPropertyAnimation(label, b"geometry")
self.animacionMostar.finished.connect(lambda: (self.parent.statusBar.showMessage(nombre), self.bloquearBotones(True)))
self.animacionMostar.setDuration(200)
self.animacionMostar.setStartValue(QRect(posicionX, 0, 640, 480))
self.animacionMostar.setEndValue(QRect(0, 0, 640, 480))
self.animacionMostar.start(QAbstractAnimation.DeleteWhenStopped)
def Limpiar(self, labelConImagen, labelMostrarImagen, imagen, nombre, posicionInternaX, posicionX=None):
def Continuar(estado):
if estado:
if posicionX:
self.Mostrar(labelMostrarImagen, imagen, nombre, posicionX)
else:
self.Mostrar(labelMostrarImagen, imagen, nombre)
self.animacionLimpiar = QPropertyAnimation(labelConImagen, b"geometry")
self.animacionLimpiar.finished.connect(lambda: labelConImagen.clear())
self.animacionLimpiar.setDuration(200)
# self.animacionLimpiar.valueChanged.connect(lambda x: print(x))
self.animacionLimpiar.stateChanged.connect(Continuar)
self.animacionLimpiar.setStartValue(QRect(0, 0, 640, 480))
self.animacionLimpiar.setEndValue(QRect(posicionInternaX, 0, 640, 480))
self.animacionLimpiar.start(QAbstractAnimation.DeleteWhenStopped)
def Cargar(self):
nombreImagen, _ = QFileDialog.getOpenFileName(self, "Seleccionar imagen", QDir.currentPath(),"Archivos de imagen (*.jpg *.png *.ico *.bmp)")
if nombreImagen:
# Verificar que QLabel tiene imagen
labelConImagen = ""
if self.labelImagen.pixmap():
labelConImagen = self.labelImagen
elif self.labelImagenUno.pixmap():
labelConImagen = self.labelImagenUno
# Si no hay imagenes disponibles marcar error
imagen = QImage(nombreImagen)
if imagen.isNull():
if labelConImagen:
self.Eliminar()
QMessageBox.information(self, "Visor de imágenes", "No se puede cargar %s." % nombreImagen)
return
# Obtener ruta de la carpeta que contiene la imagen seleccionada
self.carpetaActual = QDir(QFileInfo(nombreImagen).absoluteDir().path())
# Obtener la ruta y el nombre de las imagenes que se encuentren en la carpeta de
# la imagen seleccionada
imagenes = self.carpetaActual.entryInfoList(["*.jpg", "*.png", "*.ico", "*.bmp"], QDir.Files, QDir.Name)
self.imagenesCarpeta = [imagen.absoluteFilePath() for imagen in imagenes]
self.posicion = self.imagenesCarpeta.index(nombreImagen)
self.estadoAnterior = True if self.posicion == 0 else False
self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False
# Función encargada de bloquear o desbloquear los botones
self.bloquearBotones(False)
# Nombre y extensión de la imagen
nombre = QFileInfo(nombreImagen).fileName()
if labelConImagen:
posicionInternaX = -650
labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap() else self.labelImagenUno
self.Limpiar(labelConImagen, labelMostrarImagen, imagen, nombre, posicionInternaX)
else:
self.Mostrar(self.labelImagen, imagen, nombre)
print(os.path.abspath("Proyecto/Carpeta1"))
print(nombre)
def GuardarCarpeta1(self):
Destino=os.path.abspath("Proyecto1/Carpeta1")
i=random.randrange(10000000000)
if self.labelImagen.pixmap():
rt=self.labelImagen.pixmap()
if (os.path.exists("Proyecto1/Carpeta1/")):
rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)
elif self.labelImagenUno.pixmap():
rt=self.labelImagenUno.pixmap()
if (os.path.exists(Destino)):
rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)
def GuardarCarpeta2(self):
Destino=os.path.abspath("Proyecto1/Carpeta2")
i=random.randrange(10000000000)
if self.labelImagen.pixmap():
rt=self.labelImagen.pixmap()
if (os.path.exists("Proyecto1/Carpeta2/")):
rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)
elif self.labelImagenUno.pixmap():
rt=self.labelImagenUno.pixmap()
if (os.path.exists(Destino)):
rt.save(Destino+"\\{}.jpg".format(str(i)), quality=100)
def Eliminar(self):
def establecerValores():
labelConImagen.clear()
labelConImagen.move(0, 0)
# Limpiar la barra de estado
self.parent.statusBar.clearMessage()
# Establecer los valores predeterminados
self.posicion = int
self.estadoAnterior, self.estadoSiguiente = False, False
self.carpetaActual = QDir()
self.imagenesCarpeta.clear()
self.bloquearBotones(True)
# Verificar que QLabel tiene imagen
labelConImagen = ""
if self.labelImagen.pixmap():
labelConImagen = self.labelImagen
elif self.labelImagenUno.pixmap():
labelConImagen = self.labelImagenUno
if labelConImagen:
self.bloquearBotones(False)
self.animacionEliminar = QPropertyAnimation(labelConImagen, b"geometry")
self.animacionEliminar.finished.connect(establecerValores)
self.animacionEliminar.setDuration(200)
self.animacionEliminar.setStartValue(QRect(0, 0, 640, 480))
self.animacionEliminar.setEndValue(QRect(-650, 0, 640, 480))
self.animacionEliminar.start(QAbstractAnimation.DeleteWhenStopped)
def anteriorSiguiente(self):
if self.imagenesCarpeta:
widget = self.sender().objectName()
if widget == "Anterior":
self.estadoAnterior = True if self.posicion == 0 else False
self.estadoSiguiente = False
self.posicion -= 1 if self.posicion > 0 else 0
posicionInternaX, posicionX = 650, -650
else:
self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False
self.estadoAnterior = False
self.posicion += 1 if self.posicion < len(self.imagenesCarpeta)-1 else 0
posicionInternaX, posicionX = -650, 650
if self.estadoAnterior or self.estadoSiguiente:
return
else:
imagen = self.imagenesCarpeta[self.posicion]
# Verificar que la carpeta que contiene la imagene exista
if not QDir(self.carpetaActual).exists():
self.Eliminar()
return
elif not QFile.exists(imagen):
# Obtener la ruta y el nombre de las imagenes que se encuentren en la
# carpeta de la imagen seleccionada
imagenes = self.carpetaActual.entryInfoList(["*.jpg", "*.png", "*.ico", "*.bmp"],QDir.Files, QDir.Name)
if not imagenes:
self.Eliminar()
return
self.imagenesCarpeta = [imagen.absoluteFilePath() for imagen in imagenes]
self.posicion = randint(0, len(self.imagenesCarpeta)-1)
self.estadoAnterior = True if self.posicion == 0 else False
self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False
elif QImage(imagen).isNull():
del self.imagenesCarpeta[self.posicion]
if not self.imagenesCarpeta:
self.Eliminar()
return
self.posicion = randint(0, len(self.imagenesCarpeta)-1)
self.estadoAnterior = True if self.posicion == 0 else False
self.estadoSiguiente = True if self.posicion == len(self.imagenesCarpeta)-1 else False
imagen = self.imagenesCarpeta[self.posicion]
if self.labelImagen.pixmap():
labelConImagen = self.labelImagen
elif self.labelImagenUno.pixmap():
labelConImagen = self.labelImagenUno
# Función encargada de bloquear o desbloquear los botones
self.bloquearBotones(False)
# Nombre y extensión de la imagen
nombre = QFileInfo(imagen).fileName()
# Label en el que se va a mostrar la imagen
labelMostrarImagen = self.labelImagen if self.labelImagenUno.pixmap() else self.labelImagenUno
# Quitar la imagen actual y mostrar la siguiente
self.Limpiar(labelConImagen, labelMostrarImagen, QImage(imagen), nombre, posicionInternaX, posicionX)
# ====================== CLASE visorImagenes =======================
class visorImagenes(QMainWindow):
def __init__(self, parent=None):
super(visorImagenes, self).__init__(parent)
self.setWindowTitle("Visor de imagenes en PyQt5")
self.setWindowFlags(Qt.MSWindowsFixedSizeDialogHint)
self.setFixedSize(682, 573)
self.initUI()
def initUI(self):
# ===================== LLAMAR WIDGETS =======================
widget = Widgets(self)
self.setCentralWidget(widget)
# =============== BARRA DE ESTADO (STATUSBAR) ================
labelVersion = QLabel(self)
labelVersion.setText(" Marco Aguirre ")
self.statusBar = self.statusBar()
self.statusBar.addPermanentWidget(labelVersion, 0)
# ==================================================================
if __name__ == '__main__':
import sys
aplicacion = QApplication(sys.argv)
traductor = QTranslator(aplicacion)
lugar = QLocale.system().name()
path = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
traductor.load("qtbase_%s" % lugar, path)
aplicacion.installTranslator(traductor)
fuente = QFont()
fuente.setPointSize(10)
aplicacion.setFont(fuente)
ventana = visorImagenes()
ventana.show()
sys.exit(aplicacion.exec_())