viernes, 19 de mayo de 2017

¿CÓMO CREAR VENTANAS EMERGENTES EN PYTHON-PYQT? FORMA II


En una entrada pasada se realizó un ejercicio el cuál permitía la visualización de una ventana emergente creada desde el código, esta vez la ventana emergente se hará desde QT. Si desean ver el ejercicio anterior acá dejo el link.

La ventana principal está dada por el siguiente código:

ppal.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
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'ppal.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(362, 178)
        self.splitter = QtGui.QSplitter(Dialog)
        self.splitter.setGeometry(QtCore.QRect(70, 40, 221, 81))
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName(_fromUtf8("splitter"))
        self.label = QtGui.QLabel(self.splitter)
        self.label.setObjectName(_fromUtf8("label"))
        self.lineEdit = QtGui.QLineEdit(self.splitter)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.pushButton = QtGui.QPushButton(self.splitter)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.label.setText(_translate("Dialog", "INGRESE SU NOMBRE:", None))
        self.pushButton.setText(_translate("Dialog", "OK", None))

La ventana emergente tendrá la siguiente característica: Un botón OK, que cerrará la ventana, y un cuadro de texto que mostrará lo que se ingresó en la ventana Principal.

second.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
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'second.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(224, 108)
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(70, 60, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.label = QtGui.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(20, 20, 191, 21))
        self.label.setText(_fromUtf8(""))
        self.label.setObjectName(_fromUtf8("label"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.pushButton.setText(_translate("Dialog", "OK", None))
  
Ahora tenemos el código que ejecuta todo el ejercicio.




Espero este ejercicio les ayude y si tienen alguna duda con gusto la resolveré.

Saludos.

miércoles, 17 de mayo de 2017

¿CÓMO CREAR VENTANAS EMERGENTES EN PYTHON-PYQT? FORMA I


Ejercicio en Construcción:

Hola a todos, esta vez mostraré un ejemplo para crear ventana emergente, en la que nos mostrará un aviso.

Este ejercicio se hará tomando una ventana creada en QT como la aplicación principal, y la ventana emergente será una creada desde la consola.

PASO 1: Crear la interfaz gráfica.


Este es el código creado para la ventana principal.


ppal.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
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'ppal.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(362, 178)
        self.splitter = QtGui.QSplitter(Dialog)
        self.splitter.setGeometry(QtCore.QRect(70, 40, 221, 81))
        self.splitter.setOrientation(QtCore.Qt.Vertical)
        self.splitter.setObjectName(_fromUtf8("splitter"))
        self.label = QtGui.QLabel(self.splitter)
        self.label.setObjectName(_fromUtf8("label"))
        self.lineEdit = QtGui.QLineEdit(self.splitter)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.pushButton = QtGui.QPushButton(self.splitter)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.label.setText(_translate("Dialog", "INGRESE SU NOMBRE:", None))
        self.pushButton.setText(_translate("Dialog", "OK", None))

PASO 2: Crear el archivo ejecutable.

ejecutable.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
import sys
from ppal import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *


class EMERGENTE(QtGui.QWidget):
    def __init__(self,name=None):
        super(EMERGENTE, self).__init__()
        self.name = name
        btn1 = QtGui.QLabel("%s" % self.name,self)
        btn1.move(50, 50)
        contenedor = QVBoxLayout()
        self.setLayout(contenedor)
        btnsalir=QPushButton("salir", None)
        contenedor.addWidget(btnsalir)
        btnsalir.move(50, 50)
        self.connect(btnsalir, SIGNAL("clicked()"), self.salir)
        self.setGeometry(500, 300, 250, 180)
        self.setWindowTitle('EMERGENTE')
        self.show()
        
    def salir(self):
        self.close()

class PRINCIPAL(QtGui.QDialog):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'),self.aceptar)
        self.children = []
        self.setWindowTitle('VENTANA PRINCIPAL')
        self.show()

    def aceptar(self):
        name=self.ui.lineEdit.text()
        child= EMERGENTE(name)
        self.children.append(child)
       
 
if __name__ == '__main__':
    app=QtGui.QApplication(sys.argv)
    myapp = PRINCIPAL()
    myapp.show()
    sys.exit(app.exec_())

Resultados: Como se puede observar, al ingresar en el espacio Nombre, se abrirá una ventana emergente que mostrará la linea de texto ingresada en la ventana principal.

 Espero haya sido útil el ejercicio, y cualquier duda que tengan con gusto la resolveré.

Este ejercicio también lo voy a realizar utilizando una ventana emergente pero creada en QT. Pronto avisaré cuando esté realizada.

Salu2.

sábado, 13 de mayo de 2017

EJERCICIO DE ENCRIPTACIÓN

Buenas tardes.

Hace poco en una entrevista de trabajo me pidieron encontrar lo siguiente:


1
2
3
4
5
6
7
def encrypt(text):
total_sum = 0
total_cnt = 0
for c in text:
                total_cnt += 1
                total_sum += ord(c)**total_cnt
return total_cnt, total_sum


El código encripta una palabra, el objetivo es descifrar que palabra se ingresó con una salida dada.

Explicación del código:
Si se codifica la palabra "HOLA", La codificación de esta palabra viene dada por: ord(H)+ord(O)^2+ord(L)^3+ord(A)^4.
La función ord() devuelve el valor ASCII de un caracter.
ord(H)= 72
ord(O)^2=(79)^2 =6241
ord(L)^3=(76)^3=438976
ord(A)^4= (65)^4=17850625
HOLA=18295914

>>encrypt('HOLA')

(4,18295914)

¿Cuándo la función devuelve (4, 37348960), cual ha sido el valor del parámetro “text” ? (es mayúscula).

 Se realiza el siguiente Script.


 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
def decrypt(total_cnt, total_sum):
    a=0
    b=0
    c=0
    d=0

    A=a
    B=b**2
    C=c**3
    D=d**4

    for d in range(78,91):
        A=a
        B=b**2
        C=c**3
        D=d**4


        if A+B+C+D ==total_sum:
            print chr(a), chr(b), chr(c), chr(d)

        for c in range(69,91):
            A=a
            B=b**2
            C=c**3
            D=d**4

            if A+B+C+D ==total_sum:
                print chr(a), chr(b), chr(c), chr(d)

            for b in range(73,91):
                A=a
                B=b**2
                C=c**3
                D=d**4
                    
                if A+B+C+D ==total_sum:
                    print chr(a), chr(b), chr(c), chr(d)


                for a in range(50,91):
                    A=a
                    B=b**2
                    C=c**3
                    D=d**4
                    
                    if A+B+C+D ==total_sum:
                        print chr(a), chr(b), chr(c), chr(d)
                    
                    print A+B+C+D, A,B,C,D,a,b,c,d

y como resultado,  la palabra ingresada fue: B I E N