2 de diciembre de 2018

Animaciones 3D Unidad 4

Cubo en 3D.


import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
)

edges = (
    (0, 1),
    (0, 3),
    (0, 4),
    (2, 1),
    (2, 3),
    (2, 7),
    (6, 3),
    (6, 4),
    (6, 7),
    (5, 1),
    (5, 4),
    (5, 7)
)


def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()


def main():
    pygame.init()
    display = (800, 600)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

    gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)

    glTranslatef(0.0, 0.0, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)


main()

 

 

Cubo de colores 3D.


import sys, math, pygame
from operator import itemgetter


class Point3D:
    def __init__(self, x=0, y=0, z=0):
        self.x, self.y, self.z = float(x), float(y), float(z)

    def rotateX(self, angle):
        """ Rotates the point around the X axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        y = self.y * cosa - self.z * sina
        z = self.y * sina + self.z * cosa
        return Point3D(self.x, y, z)

    def rotateY(self, angle):
        """ Rotates the point around the Y axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        z = self.z * cosa - self.x * sina
        x = self.z * sina + self.x * cosa
        return Point3D(x, self.y, z)

    def rotateZ(self, angle):
        """ Rotates the point around the Z axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        x = self.x * cosa - self.y * sina
        y = self.x * sina + self.y * cosa
        return Point3D(x, y, self.z)

    def project(self, win_width, win_height, fov, viewer_distance):
        """ Transforms this 3D point to 2D using a perspective projection. """
        factor = fov / (viewer_distance + self.z)
        x = self.x * factor + win_width / 2
        y = -self.y * factor + win_height / 2
        return Point3D(x, y, self.z)


class Simulation:
    def __init__(self, win_width=640, win_height=480):
        pygame.init()

        self.screen = pygame.display.set_mode((win_width, win_height))
        pygame.display.set_caption("Figura de cubo 3D en python")

        self.clock = pygame.time.Clock()

        self.vertices = [
            Point3D(-1, 1, -1),
            Point3D(1, 1, -1),
            Point3D(1, -1, -1),
            Point3D(-1, -1, -1),
            Point3D(-1, 1, 1),
            Point3D(1, 1, 1),
            Point3D(1, -1, 1),
            Point3D(-1, -1, 1)
        ]

        # Define the vertices that compose each of the 6 faces. These numbers are
        #  indices to the vertices list defined above.
        self.faces = [(0, 1, 2, 3), (1, 5, 6, 2), (5, 4, 7, 6), (4, 0, 3, 7), (0, 4, 5, 1), (3, 2, 6, 7)]

        # Define colors for each face
        self.colors = [(255, 0, 100), (100, 0, 0), (0, 25, 0), (0, 0, 255), (0, 255, 155), (255, 5, 0)]

        self.angle = 0

    def run(self):
        """ Main Loop """
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            self.clock.tick(50)
            self.screen.fill((0, 32, 0))

            # It will hold transformed vertices.            \
            t = []

            for v in self.vertices:
                # Rotate the point around X axis, then around Y axis, and finally around Z axis.
                r = v.rotateX(self.angle).rotateY(self.angle).rotateZ(self.angle)
                # Transform the point from 3D to 2D
                p = r.project(self.screen.get_width(), self.screen.get_height(), 256, 4)
                # Put the point in the list of transformed vertices
                t.append(p)

            # Calculate the average Z values of each face.
            avg_z = []
            i = 0
            for f in self.faces:
                z = (t[f[0]].z + t[f[1]].z + t[f[2]].z + t[f[3]].z) / 4.0
                avg_z.append([i, z])
                i = i + 1
            # Draw the faces using the Painter's algorithm:
            #  Distant faces are drawn before the closer ones.
            for tmp in sorted(avg_z, key=itemgetter(1), reverse=True):
                face_index = tmp[0]
                f = self.faces[face_index]
                pointlist = [(t[f[0]].x, t[f[0]].y), (t[f[1]].x, t[f[1]].y),
                             (t[f[1]].x, t[f[1]].y), (t[f[2]].x, t[f[2]].y),
                             (t[f[2]].x, t[f[2]].y), (t[f[3]].x, t[f[3]].y),
                             (t[f[3]].x, t[f[3]].y), (t[f[0]].x, t[f[0]].y)]
                pygame.draw.polygon(self.screen, self.colors[face_index], pointlist)

            self.angle += 1
            pygame.display.flip()


if __name__ == "__main__":
    Simulation().run()

 


 

 

Triangulo 3D.


import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (0, 0, 1)

)

edges = (
    (4, 0),
    (4, 1),
    (4, 2),
    (4, 3),
    (0, 1),
    (0, 3),
    (2, 1),
    (2, 3)

)


def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()


def main():
    pygame.init()
    display = (800, 600)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

    gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)

    glTranslatef(0.0, 0.0, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)


main()

 

 

 

Grafica de barras.


import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (0, 0, 1)

)

edges = (
    (4, 0),
    (4, 1),
    (4, 2),
    (4, 3),
    (0, 1),
    (0, 3),
    (2, 1),
    (2, 3)

)


def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()


def main():
    pygame.init()
    display = (800, 600)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)

    gluPerspective(45, (display[0] / display[1]), 0.1, 50.0)

    glTranslatef(0.0, 0.0, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)


main()


Practicas Unidad 4

Saludo

Programa que pide un nombre y regresa un saludo con el nombre que se ingreso.

from Tkinter import *
import tkMessageBox

root = Tk()
root.geometry("500x500")
root.title("saludador")

et1 = Label(root, text = "Escribe un nombre para saludar").place(x = 160, y = 130)
entrada = StringVar()
entrada.set('')
caja11 = Entry(root, textvariable = str(entrada)).place(x = 170, y = 180)
b1 = Button(root, text = "Saludar", comman = lambda: tkMessageBox.showinfo("Message", "Hola " + entrada.get() + "!")).place(x = 200, y = 230)

root.mainloop()
 

Generador de números

Programa que genera un numero aleatorio que se le puede indicar un intervalo.
from Tkinter import *
from random import *

root = Tk()
root.geometry("500x500")
root.title("Generador de numeros")


def funcion():
    num = randint(int(aux.get()), int(aux2.get()))
    aux3.set(num)


et1 = Label(root, text="Numero 1").place(x=100, y=100)
et2 = Label(root, text="Numero 2").place(x=100, y=150)
et3 = Label(root, text="Numero generado").place(x=100, y=250)

arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
aux = StringVar()
aux2 = StringVar()
aux3 = StringVar()
s1 = Spinbox(root, textvariable=aux, values=arr1).place(x=300, y=100)
s2 = Spinbox(root, textvariable=aux2, values=arr2).place(x=300, y=150)

caja = Entry(root, textvariable=aux3).place(x=300, y=250)
b1 = Button(root, text="Generar", command=funcion).place(x=300, y=300)

root.mainloop()
 

Peliculas

En este programa se ingresan los nombres de distintas películas a una lista.
from Tkinter import *

root = Tk()
root.geometry("500x500")
root.title("Peliculas")


def fun():
    x = aux2.get()
    pelis.append(x)
    lol = OptionMenu(root, aux, *pelis).place(x=350, y=140)


et1 = Label(root, text="Escribe el titulo de una pelicula").place(x=100, y=100)
et2 = Label(root, text="Peliculas").place(x=350, y=100)
aux = StringVar()
aux.set("")
aux2 = StringVar()
pelis = [""]
lol = OptionMenu(root, aux, *pelis).place(x=350, y=140)

c1 = Entry(root, textvariable=aux2).place(x=100, y=140)
b1 = Button(root, text="Ingresar", command=fun).place(x=100, y=170)

root.mainloop()

 

Ruta de fichero

Programa que muestra el explorador de archivos para seleccionar la ruta de un archivo.
 
from Tkinter import *
from tkFileDialog import askopenfilename

root = Tk()
root.geometry("500x500")
root.title("Mostrar ruta fichero")

et1 = Label(root, text="Pulsa en el boton y elige una ruta").place(x=150, y=70)


def llamada():
    nombre = StringVar()
    nombre.set(askopenfilename())
    Entry(root, width=40, textvariable=nombre).place(x=100, y=100)


Entry(root, width=40).place(x=100, y=100)
Button(root, text="...", command=llamada).place(x=370, y=100)

root.mainloop()

 

Multiplicador

Este programa incluye campos para ingresar un valor a multiplicar por 5, 10 y/o 15 respectivamente.

# -*- coding: utf-8 -*-

from Tkinter import *


def hacer_click():
    try:
        valor = int(entrada_texto.get())
        valor = valor * 5
        etiqueta.config(text=valor)

    except ValueError:
        etiqueta.config(text="Introduzca un valor")


def hacer_click2():
    try:
        valor2 = int(entrada_texto2.get())
        valor2 = valor2 * 10
        etiqueta2.config(text=valor2)

    except ValueError:
        etiqueta2.config(text="Introduzca un valor")


def hacer_click3():
    try:
        valor3 = int(entrada_texto3.get())
        valor3 = valor3 * 15
        etiqueta3.config(text=valor3)

    except ValueError:
        etiqueta3.config(text="Introduzca un valor")


app = Tk()  # marco de la aplicacion con el obj Tk
vp = Frame(app)  # usamos el objeto frame
'''ahora le damos formato a nuestra ventana, y para eso
vamos a utilizar el metodo grid(), el cual nos va a permitir
posicionar los elementos graficos en nuestra ventana.

otro parametro que utilizaremos sera el margen: padx = (50,50)
lo cual indica 50 pixeles del lado izquierdo y 50 pixeles 
del lado derecho

luego utilizamos pady = (10,10), que son 10 pixeles en la parte
superior y 10 pixeles en la parte inferior'''

vp.grid(column=0, row=0, padx=(50, 50), pady=(10, 10))

'''luego vamos a utilizar los metodos columnconfigure()
y rowconfigure() los cuales nos van a servir para dar un
peso relativo del ancho y el alto de todos los elementos
 que se pongan en la ventana'''

vp.columnconfigure(0, weight=1)
vp.rowconfigure(0, weight=1)

'''creamos una etiqueta llamada valor y la posicionamos
con el metodo grid()'''

etiqueta = Label(vp, text="valor")  # creo un objeto etiqueta
etiqueta.grid(column=100, row=1)

etiqueta2 = Label(vp, text="valor 2")
etiqueta2.grid(column=100, row=4)

etiqueta3 = Label(vp, text="valor 3")
etiqueta3.grid(column=100, row=6)

'''creamos un boton de OK y posicionamos con grid '''

boton = Button(vp, text="Multiplicar por 5", command=hacer_click)
boton.grid(column=1, row=1)

boton1 = Button(vp, text="Multiplicar por 10", command=hacer_click2)
boton1.grid(column=1, row=4)

boton2 = Button(vp, text="Multiplicar por 15", command=hacer_click3)
boton2.grid(column=1, row=6)

valor = ""
entrada_texto = Entry(vp, width=10, textvariable=valor)
entrada_texto.grid(column=2, row=1)

valor2 = ""
entrada_texto2 = Entry(vp, width=10, textvariable=valor2)
entrada_texto2.grid(column=2, row=4)

valor3 = ""
entrada_texto3 = Entry(vp, width=10, textvariable=valor3)
entrada_texto3.grid(column=2, row=6)

app.mainloop()

 

Calendario

Muestra un calendario.

#!/usr/bin/env phyton

# - * - coding: utf - 8 -*-
# Simple calendario con tkinter


import calendar
import Tkinter as tk
import datetime

# Obtenemos los valores del ano y mes a mostrar

ano = datetime.date.today().year
mes = datetime.date.today().month


def writeCalendar(ano, mes):
    # Asignamos el ano y mes al calendario

    str1 = calendar.month(ano, mes)
    label1.configure(text=str1)


def mesAnterior():
    global mes, ano
    mes -= 1

    if ano == 0:
        mes = 12

    ano -= 1
    writeCalendar(ano, mes)


def mesSiguiente():
    global mes, ano
    mes += 1

    if mes == 13:
        mes = 1

    ano += 1

    writeCalendar(ano, mes)


root = tk.Tk()
root.title("Calendario")

# Lo posicionamos en un label

label1 = tk.Label(root, text="", font=('courier', 40, 'bold'), bg='white', justify=tk.LEFT)
label1.grid(row=1, column=1)

# ponemos los botones dentro un Frame

frame = tk.Frame(root, bd=5)
anterior = tk.Button(frame, text="Anterior", command=mesAnterior)
anterior.grid(row=1, column=1, sticky=tk.W)
siguiente = tk.Button(frame, text="Siguiente", command=mesSiguiente)
siguiente.grid(row=1, column=2)
frame.grid(row=2, column=1)

writeCalendar(ano, mes)

# ejecutamos el evento loop

root.mainloop()

 

GIF

Muestra u oculta un gif.

# Aportacion.- Alan Hernandez Mijangos
# Programa.- que toma un archivo GIF y lo muestra al hacer clic en un boton
# -*- coding: utf-8 -*-import Tkinter as tk
from Tkinter import *

ventana = Tk()
ventana.geometry('700x700')
ventana.config(bg="black")
ventana.title("Mostrando y ocultando un boton con una imagen")


def btn_hide():
    if b1.winfo_ismapped():
        b1.place_forget()
        b2.configure(text="Mostrar carita", width=15)
    else:
        b1.place(x=70, y=50)
        b2.configure(text="Ocultar carita", width=15)


imgBoton = PhotoImage(file="cajita.gif")
b1 = Button(ventana, text="Boton 1", image=imgBoton, fg="black", width=256)
b1.place(x=90, y=50)
b2 = Button(ventana, text="Ocultar carita", command=btn_hide, fg="black", width=15)
b2.place(x=130, y=280)

ventana.mainloop()


 

Texto encriptado

Este programa encripta el texto que se ingrese. También puede desencriptar el texto ingresado.

# -*- coding: utf-8 -*-
from Tkinter import *
 
# Jesus Eduardo Martinez Hinojosa
 
# Ventana
ventana = Tk()
ventana.geometry("300x300+350+80")
ventana.title("Encriptador")
ventana.resizable(width=False, height=False)
try:
    ventana.iconbitmap("icono.ico")
except:
    print("no hay icono disponible")
 
# Clave
numclave = 1
 
 
# Funciones.
def boton1():
    # Cifrado Cesar
    TAM_MAX_CLAVE = 26
 
    def obtenerModo():
        modo = "e"
        return modo
 
    def obtenerMensaje():
        mensaje = text.get("0.0", END)
        return mensaje
 
    def obtenerClave():
        global numclave
        clave = numclave
        return clave
 
    def obtenerMensajeTraducido(modo, mensaje, clave):
        if modo[0] == 'd':
            clave = -clave
        traduccion = ''
        for simbolo in mensaje:
            if simbolo.isalpha():
                num = ord(simbolo)
                num += clave
                if simbolo.isupper():
                    if num > ord('Z'):
                        num -= 26
                    elif num < ord('A'):
                        num += 26
                elif simbolo.islower():
                    if num > ord('z'):
                        num -= 26
                    elif num < ord('a'):
                        num += 26
                traduccion += chr(num)
            else:
                traduccion += simbolo
        return traduccion
 
    modo = obtenerModo()
    mensaje = obtenerMensaje()
    if modo[0] != 'b':
        clave = obtenerClave()
 
    if modo[0] != 'b':
        texto = (obtenerMensajeTraducido(modo, mensaje, clave))
        text.delete("0.0", END)
        text.insert("0.0", texto)
        informe1.config(text="Texto Encriptado")
    else:
        for clave in range(1, TAM_MAX_CLAVE + 1):
            print(clave, obtenerMensajeTraducido('desencriptar', mensaje, clave))
 
 
def boton2():
    # Cifrado Cesar
    TAM_MAX_CLAVE = 26
 
    def obtenerModo():
        modo = "d"
        return modo
 
    def obtenerMensaje():
        mensaje = text.get("0.0", END)
        return mensaje
 
    def obtenerClave():
        global numclave
        clave = numclave
        return clave
 
    def obtenerMensajeTraducido(modo, mensaje, clave):
        if modo[0] == 'd':
            clave = -clave
        traduccion = ''
        for simbolo in mensaje:
            if simbolo.isalpha():
                num = ord(simbolo)
                num += clave
                if simbolo.isupper():
                    if num > ord('Z'):
                        num -= 26
                    elif num < ord('A'):
                        num += 26
                elif simbolo.islower():
                    if num > ord('z'):
                        num -= 26
                    elif num < ord('a'):
                        num += 26
                traduccion += chr(num)
            else:
                traduccion += simbolo
        return traduccion
 
    modo = obtenerModo()
    mensaje = obtenerMensaje()
    if modo[0] != 'b':
        clave = obtenerClave()
 
    if modo[0] != 'b':
        texto = (obtenerMensajeTraducido(modo, mensaje, clave))
        text.delete("0.0", END)
        text.insert("0.0", texto)
        informe1.config(text="Texto Desencriptado")
    else:
        for clave in range(1, TAM_MAX_CLAVE + 1):
            print(clave, obtenerMensajeTraducido('desencriptar', mensaje, clave))
 
 
def salir():
    ventana.destroy()
 
 
def menu_activacion(event):
    menu_despegable.post(event.x_root, event.y_root)
 
 
def cortar():
    text.clipboard_clear()
    text.clipboard_append(text.selection_get())
    sel = text.get(SEL_FIRST, SEL_LAST)
    text.delete(SEL_FIRST, SEL_LAST)
 
 
def copiar():
    text.clipboard_clear()
    text.clipboard_append(text.selection_get())
 
 
def pegar():
    tem = text.selection_get(selection="CLIPBOARD")
    text.insert(INSERT, tem)
 
 
# Widget
b1 = Button(ventana, text="Encriptar", bg='black', fg='white', activebackground='cyan',
            activeforeground='dark slate gray', command=boton1, font=("Courier New", 9))
b2 = Button(ventana, text="Desencriptar", bg='black', fg='white', activebackground='cyan',
            activeforeground='dark slate gray', command=boton2, font=("Courier New", 9))
text = Text(ventana, fg='lavender', bg='dark slate gray', font=("Courier New", 10))
informe1 = Label(ventana, text="Ingrese un texto", bg="turquoise", font=("Courier New", 10))
 
# Empaquetado de los widget
b1.place(x=10, y=260, width=120, height=30)
b2.place(x=167, y=260, width=120, height=30)
 
informe1.place(x=0, y=0, width=300, height=30)
 
text.place(x=0, y=30, height=218, width=300)
 
# Menu popup(menu despegable)
menu_despegable = Menu(ventana, tearoff=0)
menu_despegable.add_command(label="Cortar", command=cortar, font=("Courier New", 9))
menu_despegable.add_command(label="Copiar", command=copiar, font=("Courier New", 9))
menu_despegable.add_command(label="Pegar", command=pegar, font=("Courier New", 9))
menu_despegable.add_separator()
menu_despegable.add_command(label="Salir", command=salir, font=("Courier New", 9))
 
# Evento del menu despegable
text.bind("", menu_activacion)
 
# donde mantener el enfoque.
ventana.mainloop()


 

Interés Anual

Este programa calcula el interés anual, tomando en cuenta la cantidad de dinero, el interés, y los años.

import sys
from Tkinter import *
import tkMessageBox


def interes():
    v1 = int(ent1.get())
    v2 = int(ent2.get())
    v3 = int(ent3.get())
    r = v1 * v2 / 100
    g = (r * v3)
    f = g + v1
    print "Cuando pasen", v3, "anos, con un interes de", v2, " usted habra generado", f, "pesos"


v = Tk()
v.title("Interes")
v.geometry("400x250")

vp = Frame(v)
vp.grid(column=0, row=0, padx=(50, 50), pady=(10, 10))
vp.columnconfigure(0, weight=1)
vp.rowconfigure(0, weight=1)

e1 = Label(vp, text="Pesos:")
e1.grid(row=2, column=4, padx=(20, 20), pady=(20, 20))

e2 = Label(vp, text="Interes:")
e2.grid(row=3, column=4, padx=(20, 20), pady=(20, 20))

e3 = Label(vp, text="Anos:")
e3.grid(row=4, column=4, padx=(20, 20), pady=(20, 20))

val1 = ""
ent1 = Entry(vp, width=12, textvariable=val1)
ent1.grid(row=2, column=5)

val2 = ""
ent2 = Entry(vp, width=12, textvariable=val2)
ent2.grid(row=3, column=5)

val3 = ""
ent3 = Entry(vp, width=12, textvariable=val3)
ent3.grid(row=4, column=5)

b1 = Button(vp, text="Calcular", command=interes)
b1.grid(row=5, column=5, padx=(20, 20), pady=(20, 20))

v.mainloop()

 

Datos basicos

Interfaz con campos para ingresar nombre, apellido y correo.

# Aportacion.- Luis Angel Alonso Rojas
# programa que hace la interfaz
# programa que te pide tus datos basicos
# Luis Angel Alonso Rojas#15260607

from Tkinter import *

root = Tk()
root.title('formulario 1')
nombre_label = Label(root, text="Nombre :")
nombre_label.grid(row=1, column=1)
nombre_str = StringVar()
nombre_entry = Entry(root, textvariable=nombre_str)
nombre_entry.grid(row=1, column=2)
last_label = Label(root, text="Apellido : ")
last_label.grid(row=2, column=1)
last_str = StringVar()
last_entry = Entry(root, textvariable=last_str)
last_entry.grid(row=2, column=2)
mail_label = Label(root, text="Email : ")
mail_label.grid(row=3, column=1)
mail_str = StringVar()
mail_entry = Entry(root, textvariable=mail_str)
mail_entry.grid(row=3, column=2)
endfinish = Button(root, text="finalizar", relief=FLAT)
endfinish.grid(row=4, column=2)
root.mainloop()

 

Lista de peliculas

En este programa se le pide al usuario que escriba el nombre de una película y su clasificación, después de agregarlas se muestra un menú en el que se puede elegir la cantidad de días que se puede rentar. Utiliza listas, y ventanas de información, advertencia y error.

# coding=utf-8
# Aportacion de Brandon Asael Cerda Hernandez
# Programa: con listas, combo box, agrega a la lista las peliculas al guardar
# excelente programa en python!!!


# -*- coding: utf-8 -*-from Tkinter import Label,Entry,Button,Tk,Frame,W,N,S,E,END,HORIZONTAL,Spinbox

from ttk import *
from tkMessageBox import askyesno, showinfo, showerror;
from Tkinter import *


# en el import, solo estoy pidiendo importar los elementos que vamos a usar, para no usar el * sin necesidad de traer mas elementos
def AddEntryMovie():
    Movie = CatchMovie.get()
    if (CatchMovie.get() == ""):
        CatchMovie.config(bg="red")
        showerror("What Movie is it?", "Por favor ingresa una pelicula! no dejes el campo en blanco!")
        CatchMovie.config(bg="white")

    if (Classes.get() == ""):
        # otra pequeña "excepcion" por si la clasificación de la pelicula no tiene seleccionada una clasificacion
        showerror("What Movie is it?", "Por favor selecciona una clasificación!")

    if (askyesno("Are you sure?",
                 "Deseas añadir esta pelicula: \n\"" + Movie + "\"\nA la lista de peliculas?") == True):
        values = list(MoviesOnList["values"])
        # se crea dentro de la funcion la Variable "values" que sera una lista de los valores que se encuentran en la lista despegable
        MoviesOnList["values"] = values + [Movie]
        # de la lista despegalble agregamos el nuevo valor que esta en nuestro campo de texto, para esto debemos ponerlo entre                #  [] para que se interprete como el valor de una lista y pueda sumarse a la lista despegable de peliculas
        Classifications.insert(i, Classes.get())
        # añade la clasificiación a una lista, para asi tenerla disponible en la Lista Despegable de Peliculas disponibles
        Mov.insert(i, Movie)
        i + 1
        CatchMovie.delete(0, END)
        # ya lo hemos visto antes pero lo explicare aun asi, .delete(0, END) borra el texto dentro del Entry
        CatchMovie.insert(0, "")
        # Aqui es casi lo mismo, pero deja el campo Vacio y usable, tambien para evitar errores de captura
        Classes.set("")
        # Reinicia la Lista Despegable de las clasificaciones

        showinfo("Exito!", "Has anadido: \"" + Movie + "\" A la lista de Peliculas")
    else:
        showinfo("Guess No", "La Pelicula: " + Movie + " No será añadida")


def firstDone():
    if (askyesno("Are you sure?",
                 "ADVERTENCIA: ESTA ACCION NO PUEDE SER DESHECHA" "\nSi de verdad ya terminaste te agregar peliculas, prosigue, si no, DETENTE!") == True):
        CatchMovie.config(state="disable")
        Classes.config(state="disable")
        AddMov.config(state="disable")
        Done.config(state="disable")
        # tambien se habia visto antes, pero explicare aun asi, el 'state' "disable" deshabilita el componente del frame        app.geometry("600x300")
        # se puede cambiar la dimension de una ventana, aunque se haya establecido un tamaño, esto nos permite controlar la ventana y los componentes a mostrar
        MovietoRent.grid()
        MoviesOnList.grid()
        ClassifiedAs.grid()
        AskRent.grid()
        Days4Rent.grid()
        Rent.grid()
        # simplemente con .grid() vuelvo a colocar en su respectivo lugar, los elementos que no son visibles para el usuario, ocultos con '.grid_remove()'
        showinfo("", "Puedes seguir agregando peliculas si gustas!")


def MovieSel(self):
    ClassifiedAs.config(state="normal")
    # para que un Entry pueda mostrar un texto, es necesario que este en un estado normal (state="normal")
    ClassifiedAs.delete(0, END)
    ClassifiedAs.insert(0, Classifications.__getitem__(Mov.index(MoviesOnList.get())))
    # aqui se hace uso de la Lista [] y el atributo "__getitem__()" para obtener lo que este en la lista, para ello    #es necesario poner un indice numerico, asi que utilizando ".index()" puedo llamar solo el indice (numero en la lista)    #y .__getitem__() obtendra el objeto que este en ese indice de la lista, para asi poder mostrar la clasificación correecta    ClassifiedAs.config(state="readonly")
    # al cambiar el estado a "Solo Lectura" (state="readonly") el Entry solo mostrara Texto, pero no permitira la entrada de datos o textos


def RentAMovie():
    if (askyesno("You ready?", "Deseas Rentar la pelicula: " + MoviesOnList.get() +
                               "\n por " + Days4Rent.get() + " Dia/s?") == True):
        if (ClassifiedAs.get() == "Adultos"):
            if (askyesno("Age Issue", "Eres Mayor de Edad?") == True):
                showinfo("Ask for: ", "Presente su Identificación")
            else:
                showerror("Get outta here", "NO SE RENTAN PELICULAS A MENORES")
        else:
            showinfo("Have a nice day!", "Disfruta de tu pelicula! \nQue tengas un Buen dia :)")
    else:
        showinfo("Ok?", "De acuerdo, revisa tus opciones entonces :)")


app = Tk()
app.geometry("600x120")
app.title("Lista de Peliculas")
vp = Frame(app)
vp.grid(column=0, row=0, padx=(30, 30), pady=(20, 20))
vp.rowconfigure(0, weight=1)
vp.columnconfigure(0, weight=1)
Classified = Label(vp, text="Clasificación")
Classified.grid(column=2, row=1, padx=(10, 10), pady=(10, 10))
AskMov = Label(vp, text="Ingrese una Pelicula: ")
AskMov.grid(column=1, row=1, padx=(10, 10), pady=(10, 10), sticky=W)
cMovie = StringVar
CatchMovie = Entry(vp, textvariable=cMovie, width=35)
CatchMovie.grid(column=1, row=2, padx=(10, 10), pady=(10, 10))
AddMov = Button(vp, text="Añadir", command=AddEntryMovie)
AddMov.grid(column=3, row=2, padx=(10, 10), pady=(10, 10))
Done = Button(vp, text="Finalizar", command=firstDone)
Done.grid(column=4, row=2, padx=(10, 10), pady=(10, 10))
Classes = Combobox(vp, state="readonly")
Classes.grid(column=2, row=2, padx=(10, 10), pady=(10, 10))
Classes["values"] = ["Para todas las Edades", "Familiar", "Mayores de 10", "Adolescentes", "Mayores de 15", "Adultos"]
Separator(vp, orient=HORIZONTAL).grid(column=1, row=3, columnspan=4, sticky=W + E, pady=(10, 10))
MovietoRent = Label(vp, text="Pelicula a Rentar: ")
MovietoRent.grid(column=1, row=4, padx=(10, 10), pady=(30, 10), stick=W)
MovietoRent.grid_remove()
MoviesOnList = Combobox(vp, state="readonly")
MoviesOnList.grid(column=1, row=5, padx=(10, 10), pady=(10, 10), sticky=W + E)
MoviesOnList.bind(MovieSel)
MoviesOnList.grid_remove()
ClassifiedAs = Entry(vp, state="readonly")
ClassifiedAs.grid(column=2, row=5, padx=(10, 10), pady=(10, 10), sticky=W + E)
ClassifiedAs.grid_remove()
AskRent = Label(vp, text="Dias\n a Rentar")
AskRent.grid(column=3, row=4, padx=(10, 10), pady=(10, 10))
AskRent.grid_remove()
Days4Rent = Spinbox(vp, width=5, from_=1, to=7)
Days4Rent.grid(column=3, row=5, padx=(10, 10), pady=(10, 10), sticky=N + S)
Days4Rent.grid_remove()
Rent = Button(vp, text="Rentar", command=RentAMovie)
Rent.grid(column=4, row=5, padx=(10, 10), pady=(10, 10))
Rent.grid_remove()
Classifications = []
Mov = []
i = int(0)
app.mainloop()

 

Indice de masa corporal

Se ingresa el peso y la altura para calcular el IMC.

# Aportacion de Cecilia Abigal Cantu Alcala
# programa que calcula IMC

# -*- coding: utf-8 -*-import sys
import Tkinter
from Tkinter import *
import tkMessageBox


def imc():
    num1 = int(entrada_peso.get())
    num2 = float(entrada_altura.get())
    imc = (num1 / (num2 * num2))

    if imc == 0 or imc < 18:
        tkMessageBox.showinfo("Resultado", "Peso bajo. Necesario valorar signos de desnutricion")

    elif imc == 18 or imc < 25:
        tkMessageBox.showinfo("Resultado", "Usted tiene un peso normal")

    elif imc == 25 or imc < 27:
        tkMessageBox.showinfo("Resultado", "Usted padece sobrepeso")

    elif imc == 27 or imc < 30:
        tkMessageBox.showinfo("Resultado", "Usted padece obesidad grado I")

    elif imc == 30 or imc < 40:
        tkMessageBox.showinfo("Resultado", "Usted padece de obesidad grado II")

    else:
        tkMessageBox.showinfo("Resultado", "Usted padece de obesidad morbida")


ventana = Tk()
ventana.title("Calculo de IMC")
ventana.geometry("400x200")
ventana.config(bg="rosybrown")

vp = Frame(ventana)
vp.grid(column=0, row=0, padx=(50, 50),
        pady=(10, 10))  # para posicionar cualquier objetovp.columnconfigure(0, weight=1)
vp.rowconfigure(0, weight=1)

peso = IntVar()
altura = float()

etiqueta_peso = Label(ventana, text='Peso(kg):', bg='ivory')
etiqueta_peso.grid(row=1, column=1, padx=(10, 10), pady=(10, 10), sticky=E)

entrada_peso = Entry(ventana, textvariable=peso)
entrada_peso.grid(row=1, column=2, padx=(10, 10), pady=(10, 10), sticky=E)

etiqueta_altura = Label(ventana, text='Altura(mts): ', bg='ivory')
etiqueta_altura.grid(row=2, column=1, padx=(10, 10), pady=(10, 10), sticky=E)

entrada_altura = Entry(ventana, textvariable=altura)
entrada_altura.grid(row=2, column=2, padx=(10, 10), pady=(10, 10), sticky=E)

bconv = Button(ventana, bg='plum', fg='white', text='Calcular IMC', width=10, height=1, command=imc)
bconv.grid(row=4, column=2, padx=(10, 10), pady=(10, 10))

ventana.mainloop()

 

Signo zodiacal

Este programa te dice cuál es tu signo zodiacal al ingresar tu día y mes.

# Aportacion de Cecilia Abigal Cantu Alcala
# programa que saca el signo zodiacal

import sys
import Tkinter as tk
from Tkinter import *
import tkMessageBox

ventana = Tk()
ventana.title("Signo Zodiacal")
ventana.geometry("400x200")
ventana.config(bg="rosybrown")

vp = Frame(ventana)
vp.grid(column=0, row=0, padx=(50, 50),
        pady=(10, 10))  # para posicionar cualquier objetovp.columnconfigure(0, weight=1)
vp.rowconfigure(0, weight=1)

var = StringVar(ventana)
ver = StringVar(ventana)
var.set("Enero")  # initial valuever = StringVar(ventana)
ver.set("1")  # initial value
etiqueta_mes = Label(ventana, text='Mes de nacimiento: ')
ent_mes = OptionMenu(ventana, var, "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto",
                     "Septiembre", "Octubre", "Noviembre", "Diciembre", )
etiqueta_mes.grid(row=1, column=1, padx=(10, 10), pady=(10, 10), sticky=E)
ent_mes.grid(row=1, column=3)

etiqueta_dia = Label(ventana, text='Dia de nacimiento: ')
ent_dia = OptionMenu(ventana, ver, "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")
etiqueta_dia.grid(row=4, column=1, padx=(10, 10), pady=(10, 10), sticky=E)
ent_dia.grid(row=4, column=3)


def signo():
    month = str(var.get())
    day = int(ver.get())
    if month == "Marzo" and day >= 21 or month == "Abril" and day <= 20:
        tkMessageBox.showinfo("Signo", "Eres Aries")
    elif month == "Abril" and day >= 21 or month == "Mayo" and day <= 21:
        tkMessageBox.showinfo("Signo", "Eres Tauro")
    elif month == "Mayo" and day >= 22 or month == "Junio" and day <= 21:
        tkMessageBox.showinfo("Signo", "Eres Gemenis")
    elif month == "Junio" and day >= 22 or month == "Julio" and day <= 22:
        tkMessageBox.showinfo("Signo", "Eres Cancer")
    if month == "Julio" and day >= 23 or month == "Agosto" and day <= 23:
        tkMessageBox.showinfo("Signo", "Eres Leo")
    if month == "Agosto" and day >= 24 or month == "Septiembre" and day <= 23:
        tkMessageBox.showinfo("Signo", "Eres Virgo")
    if month == "Septiembre" and day >= 24 or month == "Octubre" and day <= 23:
        tkMessageBox.showinfo("Signo", "Eres Libra")
    if month == "Octubre" and day >= 24 or month == "Noviembre" and day <= 22:
        tkMessageBox.showinfo("Signo", "Eres Escorpion")
    if month == "Noviembre" and day >= 23 or month == "Diciembre" and day <= 21:
        tkMessageBox.showinfo("Signo", "Eres Sagitario")
    if month == "Diciembre" and day >= 22 or month == "Enero" and day <= 20:
        tkMessageBox.showinfo("Signo", "Eres Capricornio")
    if month == "Enero" and day >= 21 or month == "Febrero" and day <= 18:
        tkMessageBox.showinfo("Signo", "Eres Acuario")
    if month == "Febrero" and day >= 19 or month == "Marzo" and day <= 20:
        tkMessageBox.showinfo("Signo", "Eres Piscis")


boton = Button(ventana, text='Signo', command=signo, width=20)
boton.grid(row=5, column=1, padx=(10, 10), pady=(10, 10), sticky=E)

ventana.mainloop()

 

Contador dinero

En este programa podemos ingresar la cantidad de billetes o monedas para calcular el total del dinero.

# Programa punto de venta, cuenta billetes, monedas etc...
# Aportacion de: Jose Manuel Sanchez Izaguirre
from Tkinter import *
import tkMessageBox


def SumMul():
    try:
        _e0 = int(v0.get())
        _e0 = _e0 * .50
        _e1 = int(v1.get())
        _e1 = _e1 * 1
        _e2 = int(v2.get())
        _e2 = _e2 * 2
        _e3 = int(v3.get())
        _e3 = _e3 * 5
        _e4 = int(v4.get())
        _e4 = _e4 * 10
        _e5 = int(v5.get())
        _e5 = _e5 * 20
        _e6 = int(v6.get())
        _e6 = _e6 * 50
        _e7 = int(v7.get())
        _e7 = _e7 * 100
        _e8 = int(v8.get())
        _e8 = _e8 * 200
        _e9 = int(v9.get())
        _e9 = _e9 * 500
        _e10 = _e0 + _e1 + _e2 + _e3 + _e4 + _e5 + _e6 + _e7 + _e8 + _e9
        tkMessageBox.showinfo("El resultado es", _e10)
    except ValueError:
        etiqueta.config(text="Introduce un numero entero")


v = Tk()
v.title("")
v.geometry("200x350")

vp = Frame(v)
vp.grid(column=0, row=0, padx=(50, 50), pady=(10, 10))
vp.columnconfigure(0, weight=1)
vp.rowconfigure(0, weight=1)

ET0 = Label(vp, text="MONEDAS")
ET0.grid(column=2, row=1)

e0 = Label(vp, text="0.50")
e0.grid(column=1, row=3)

e1 = Label(vp, text="1.00")
e1.grid(column=1, row=4)

e2 = Label(vp, text="2.00")
e2.grid(column=1, row=5)

e3 = Label(vp, text="5.00")
e3.grid(column=1, row=6)

e4 = Label(vp, text="10.00")
e4.grid(column=1, row=7)

v0 = Entry(vp, width=5, textvariable=e0)
v0.grid(row=3, column=2)

v1 = Entry(vp, width=5, textvariable=e1)
v1.grid(row=4, column=2)

v2 = Entry(vp, width=5, textvariable=e2)
v2.grid(row=5, column=2)

v3 = Entry(vp, width=5, textvariable=e3)
v3.grid(row=6, column=2)

v4 = Entry(vp, width=5, textvariable=e4)
v4.grid(row=7, column=2)

ET1 = Label(vp, text="BILLETES")
ET1.grid(column=2, row=9)

e5 = Label(vp, text="20.00")
e5.grid(column=1, row=11)

e6 = Label(vp, text="50.00")
e6.grid(column=1, row=12)

e7 = Label(vp, text="100.00")
e7.grid(column=1, row=13)

e8 = Label(vp, text="200.00")
e8.grid(column=1, row=14)

e9 = Label(vp, text="500.00")
e9.grid(column=1, row=15)

v5 = Entry(vp, width=5, textvariable=e5)
v5.grid(row=11, column=2)

v6 = Entry(vp, width=5, textvariable=e6)
v6.grid(row=12, column=2)

v7 = Entry(vp, width=5, textvariable=e7)
v7.grid(row=13, column=2)

v8 = Entry(vp, width=5, textvariable=e8)
v8.grid(row=14, column=2)

v9 = Entry(vp, width=5, textvariable=e9)
v9.grid(row=15, column=2)

b = Button(vp, text="TOTAL", command=SumMul)
b.grid(row=17, column=2, padx=(20, 20), pady=(20, 20))

v.mainloop()

 

Edad con Spinbox

Este programa utiliza un Spinbox para seleccionar un número (en este caso, el año de nacimiento).

# Ejemplo de Edad con Spinbox.-
# Aportacion de: Valeria Esmeralda Vargas Requena
import sys
from Tkinter import *
import tkMessageBox


def CalcularEdad():
    Valor = int(CajaEdad.get())
    if (2018 - Valor >= 18):
        tkMessageBox.showinfo("Felicidades", "Eres Mayor de Edad!")
    elif (2018 - Valor <= 5):
        tkMessageBox.showinfo("Eehhh?", "Como puedes tener menos de 5  y usar este programa")
    elif ((2018 - Valor) > 8 and (2018 - Valor) < 18):
        tkMessageBox.showinfo("Alejate!", "Aun no posees la edad suficiente para seguir!")


ventana = Tk()
ventana.title("Mayor de edad")
ventana.geometry("600x400")

vp = Frame(ventana)  # estamos utilizando el objeto framevp.grid(column=0, row=0, padx =(50,50), pady=(10,10))
vp.grid(column=0, row=0, padx=(50, 50), pady=(10, 10))
vp.columnconfigure(0, weigh=1)
vp.rowconfigure(0, weight=1)

PreguntarEdad = Label(vp, text="Por favor ingrese su fecha de Nacimiento")
PreguntarEdad.grid(column=1, row=1, padx=(10, 10), pady=(10, 10))

CajaEdad = Spinbox(vp, from_=1980, to=2018, width=10)
CajaEdad.grid(column=2, row=1, padx=(10, 10), pady=(10, 10), sticky=N + S)

BotonCalcular = Button(vp, text="Calcular!", command=CalcularEdad)
BotonCalcular.grid(column=3, row=1, padx=(10, 10), pady=(10, 10))

ventana.mainloop()

2 de octubre de 2018

Codigo con estilo.

En esta entrada les explicare como hacer para que su código en Python se muestre de una manera mas estilizada que facilitara la visualización y compartir el código fuente separando y enumerando las lineas.


  1. Primero, en el menú lateral buscamos y seleccionamos la opción "Tema".


    2 . Seleccionamos la opción "Editar HTML".

      

    3. Buscamos la linea de código donde este "<head>".


    Y copiamos el siguiente código como se muestra en la imagen anterior:

    <!--SYNTAX HIGHLIGHTER INICIO-->
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
    <link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
    <script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
    <script language='javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.config.clipboardSwf = &quot;http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf&quot;;
    SyntaxHighlighter.all();
    </script>
    <!--SYNTAX HIGHLIGHTER FIN-->

    Hacen clic en "Guardar tema".

    5. Al crear una nueva entrada, para agregar codigo tienen que hacer clic en HTML y escribir:

    <pre class="brush: python">

    #Inserta tu codigo aqui

    </pre>

    De esa manera podrán agregar el código para que se muestre de una manera mas atractiva y amigable con los usuarios que visiten su blog.

Practica 25: Creacion de un poligono

from Tkinter import *

ventana=Tk()
ventana.title('Hacer un pentagono')
ventana.config(bg='gray')
ventana.geometry('500x500')

def poligono(ventana):
    panel = Canvas(width = 500, height = 400, bg='white')
    panel.pack()
    panel.create_polygon(140, 40, 300, 40, 400, 140, 40, 140,  width = 5, fill= 'white', outline = 'black' )

boton1 = Button(ventana, text = 'Hacer poligono', command = lambda:poligono(ventana))
boton1.pack()

ventana.mainloop()