TRIANGULO 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),
    (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()

CUBO DE COLORES EN 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()

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()

GRÁFICA DE BARRAS

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt


fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')

xpos = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
ypos = [2,3,4,5,1,6,2,1,7,2,3,5,1,3,2]
num_elements = len(xpos)
zpos = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
dx = dy =dz = [20,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

ax1.bar3d(xpos, ypos, zpos, dx, dy, dz, color='red')
plt.show()

Programas hechos desde cero

1.  Programa que pide el nombre de una persona y la salud.


from Tkinter import *
from tkMessageBox import *
 
ventana=Tk()
ventana.geometry("300x300")
ventana.title('Hola.........')
nombre= StringVar()
nombre.set('')
dato=Entry(ventana,textvariable=str(nombre)).place(x=100,y=100)
button=Button(ventana,text='hola',command=lambda:showinfo(title='hola', message='hola '+ nombre.get())).place(x=100,y=150)
 
ventana.mainloop()




2.  Programa que abre el explorador de archivos.


from Tkinter import *
from PIL import *
from tkFileDialog import askopenfilename
 
 
ventana=Tk()
ventana.geometry('450x300')
 
def llamada():
    hey = StringVar()
    nombre = askopenfilename()
    print nombre
    hey.set(nombre)
    label = Entry(ventana, textvariable=hey,width=50).place(x=100, y=100)
 
 
nombre=Label(ventana,text='pulse el boton y elija una ruta').place(x=10,y=10)
 
label=Entry(ventana,textvariable='').place(x=100,y=100)
button=Button(ventana,text='...',command=lambda:llamada()).place(x=150,y=150)
 
 
 
 
ventana.mainloop()





3. Programa que muestra la multiplicación de un numero




from Tkinter import *
app=Tk()#de la aplicacion con el objeto Tk()
vp=Frame(app)#utilizamos el objeto frame
def hacerclick():
    try:
        print 'funcionhacerclick1'
        valor=int(entrada_texto.get())
        valor=valor*5
        etiqueta1.config(text=valor)
 
    except ValueError:
        etiqueta1.config(text='introduce un valor')
 
def hacerclick2():
    try:
        print 'funcionhacerclick2'
        valor=int(entrada_texto.get())
        valor=valor*10
        etiqueta2.config(text=valor)
 
    except ValueError:
        etiqueta2.config(text='introduce un valor')
 
def hacerclick3():
    try:
        print 'funcionhacerclick3'
        valor=int(entrada_texto.get())
        valor=valor*15
        etiqueta3.config(text=valor)
 
    except ValueError:
        etiqueta3.config(text='introduce un valor')
 
 
 
'''hora 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
 
y despues utilizamos pady=(10,10) que son diez pixeles en la parte superior y diez pixeles en la
parte inferior'''
 
vp.grid(column=0,row=0,padx=(50,50),pady=(10,10))
 
'''luegovamos a utilizar los metodos columnfigure()
rowconfigure(),los cuales nos van a servir para dar
un peso relativo del ancho y el alto de todos los elementos
que se añadan a la ventana'''
 
vp.columnconfigure(0,weight=1)
vp.rowconfigure(0,weight=1)
 
'''creamos una etiqueta llamada valor y la posicionamos en el frame 
con el metodo grid()'''
 
etiqueta1=Label(vp,text='valor1')#creo un objeto para usar una etiqueta
etiqueta1.grid(column=100,row=2)#le da posicionamiento en la pantalla y no dentro del frame
 
etiqueta2=Label(vp,text='valor2')
etiqueta2.grid(column=100,row=4)
 
etiqueta3=Label(vp,text='valor3')
etiqueta3.grid(column=100,row=6)
 
'''creamos un boton de  y lo posicionamos con grid'''
boton=Button(vp,text='multiplicar por 5',command=hacerclick)
boton.grid(column=1,row=2)
 
boton=Button(vp,text='multiplicar por 10',command=hacerclick2)
boton.grid(column=1,row=4)
 
boton=Button(vp,text='multiplicar por 5',command=hacerclick3)
boton.grid(column=1,row=6)
 
'''creamos una caja de texto'''
 
valor=''
entrada_texto=Entry(vp,width=10,textvariable=valor)
entrada_texto.grid(column=10,row=10)
app.mainloop()











4.  Programa que al introducir un texto y oprimir un boton lo guarde en un option menu




from Tkinter import *
 
ventana=Tk()
ventana.geometry('400x200')
ventana.title('introducir pelis')
wow=StringVar()
global pelicula
arreglopelis=[]
def introducirpeliculas(pelicula,f):
    if pelicula.get()!='':
        n=0
        while f==1:
            agregar=pelicula.get()
            arreglopelis.insert(n,agregar)
 
            Opciones = OptionMenu(ventana,wow,*arreglopelis ).place(x=200, y=50)#ventana,una variable auxiliar que se usa para guardar el dato y el array
            n+=1
            break
 
pelicula=StringVar()
et2=Label(ventana,text='introduzca el nombre').place(x=10,y=10)
texto=Entry(ventana,textvariable=str(pelicula)).place(x=10,y=30)
print pelicula.get()#para saber que guardo
et1=Label(ventana,text='lista de peliculas').place(x=200,y=10)
boton=Button(ventana,text='introducir',command=lambda:introducirpeliculas(pelicula,f=1)).place(x=10,y=100)
 
ventana.mainloop()


[UNIDAD 4]: PROGRAMAS CORREGIDOS

1.  Programa que pide datos básicos de una persona.


from Tkinter import *
root = Tk()
root.geometry('250x150')
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()


2.  Programa que calcula el IMC de una persona.




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()
3.  Programa que dice el signo zodiacal de una persona.







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)
var.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()
4.  Programa que cuenta billetes y monedas.






[Adivina la pelicula] [Aportación propia]





from Tkinter import *
from PIL import Image, ImageTk
import os
import random
import pygame
import threading
import Tkinter
import time

"""DIRECTORIO DE  LAS IMAGENES"""
dir = os.path.dirname(__file__)
fotos = dir + "/peliculas/"
root = Tk()
arreglo = [1, 2, 3, 4]
eleccion = str(arreglo.index(random.choice(arreglo)) + 1)
print eleccion
figura = fotos + eleccion + ".jpg"
print figura



img = Image.open(figura)  # objeto para poder abrir la figura
tkimage = ImageTk.PhotoImage(img)  # muestra la imagen
etiqueta = Label(root, image=tkimage).place(x=100, y=150)  # Coloca una imagen en una etiqueta

    # cargar la etiqueta para que se pueda desplegar

def Ver():
    print(var.get())
    s = var.get()

    if s == "p1":
        if figura == "C:/CHIO/peliculas/1.jpg":
            root = Tk()
            lbl = Label(root, text='BIEN HECHO')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
        else:
            root = Tk()
            lbl = Label(root, text='INCORRECTO. PRUEBA UNA VEZ MAS')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
            root.title('RESPUESTA')


    elif s == "p2":
        if figura == "C:/CHIO/peliculas/2.jpg":
            root = Tk()
            lbl = Label(root, text='BIEN HECHO')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
        else:
            root = Tk()
            lbl = Label(root, text='INCORRECTO. PRUEBA UNA VEZ MAS')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
            root.title('RESPUESTA')



    elif s == "p3":
        if figura == "C:/CHIO/peliculas/3.jpg":
            root = Tk()
            lbl = Label(root, text='BIEN HECHO')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
        else:
            root = Tk()
            lbl = Label(root, text='INCORRECTO. PRUEBA UNA VEZ MAS')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
        root.title('RESPUESTA')



    else:
        if figura == "C:/CHIO/peliculas/4.jpg":
            root = Tk()
            lbl = Label(root, text='BIEN HECHO')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
        else:
            root = Tk()
            lbl = Label(root, text='INCORRECTO. PRUEBA UNA VEZ MAS')
            lbl.pack()
            btn = Button(root, text='Ok', command=root.quit)
            btn.pack()
        root.title('RESPUESTA')



labelfont = ('Matura MT Script Capitals', 20, 'bold')
widget = Label(root, text='Adivina la pelicula')
widget.config(font=labelfont)
widget.place(x=350, y=50)



labelfont = ('Bookman Old Style', 10, 'bold')
widget = Label(root, text='A QUE PELICULA PERTENECE LOS\n'
                                'SIGUIENTES PERSONAJES?')
widget.config(font=labelfont)
widget.place(x=705, y=150)


var = StringVar()
labelfont = ('Ink Free', 10, 'bold')
rad0 = Radiobutton(root, text="Harry Potter", variable=var, value="p1", command=Ver, font=labelfont)
rad0.place(x=710, y=250)
rad1 = Radiobutton(root, text="Cazadores de sombras", variable=var, value="p2", command=Ver, font=labelfont)
rad1.place(x=710, y=300)
rad2 = Radiobutton(root, text="The Vampire Diaries", variable=var, value="p3", command=Ver, font=labelfont)
rad2.place(x=710, y=350)
rad3 = Radiobutton(root, text="Avengers", variable=var, value="p4", command=Ver, font=labelfont)
rad3.place(x=710, y=400)



var.set(' ')
root.geometry("951x800")
root.mainloop()

PRACTICA 50





#!/usr/bin/python
# -*- coding: utf-8 -*-
# www.pythondiario.com
 
import sys #importacion de la libreria sys
from Tkinter import * #importacion del modulo tkinter
 
 
def hacer_click(): #se crea una funcion
    try: #funciona en caso de que se ingrese a la caja de texto un valor diferente a un numero
        _valor = int(entrada_texto.get()) #captura lo que se ingrese a la caja de texto y lo guarda en _valor
        _valor = _valor * 5 #multiplica por 5 lo capturado por la caja y lo guarda en _valor
        etiqueta.config(text=_valor) #modifica la etiqueta por el valor resultante al multiplicar por 5
    except ValueError: #es parte del try, y se utiliza en caso de que se ingrese un valor distinto a un numero
        etiqueta.config(text="Introduce un numero!") #muestra una etiqueta y manda un mensaje
 
 
app = Tk() #se crea la ventana de la app
app.title("Mi segunda App Grafica") #se le da titulo a la ventana
 
# Ventana Principal
vp = Frame(app) #organiza y da formato a la ventana
vp.grid(column=0, row=0, padx=(50, 50), pady=(10, 10)) #posiciona los elementos graficos en nuestra ventana
vp.columnconfigure(0, weight=1) #da un peso relativo al ancho y alto de todos los elementos que se pongan en la ventana
vp.rowconfigure(0, weight=1) #da un peso relativo al ancho y alto de todos los elementos que se pongan en la ventana
 
etiqueta = Label(vp, text="Valor") #se crea una etiqueta
etiqueta.grid(column=2, row=2, sticky=(W, E)) #se posiciona la etiqueta
 
boton = Button(vp, text="OK!", command=hacer_click) #se crea un boton que accionara la funcion hacer_click
boton.grid(column=1, row=1) #se posiciona el boton
 
valor = "" #se crea una variable
entrada_texto = Entry(vp, width=10, textvariable=valor) #se crea una caja de texto para ingresar datos
entrada_texto.grid(column=2, row=1) #se posiciona la caja de texto
 
app.mainloop() #ejecuta la ventana para que se pueda visualizar

PRACTICA 49: CREAR UNA VENTANA, BOTÓN Y ETIQUETA




#!/usr/bin/python
# -*- coding: utf-8 -*-
# www.pythondiario.com
 
from Tkinter import *
 
app = Tk()
app.title("Aplicacion grafica en python")
etiqueta = Label(app, text="Hola mundo!!!")
boton = Button(app, text="OK!!")
 
etiqueta.pack()
boton.pack()
app.mainloop()

PRACTICA 48: ABRIR UN ARCHIVO







#!/usr/bin/python
# -*- coding: utf-8 -*-
# www.pythondiario.com
 
from Tkinter import *
from tkFileDialog import askopenfilename
 
 
def llamada():
    nombre = askopenfilename()
    print nombre
 
 
errmsg = 'Error!'
Button(text='Abrir archivo', command=llamada).pack(fill=X)
mainloop()

PRACTICA 47: CAJA DE DIALOGO













#!/usr/bin/python
# -*- coding: utf-8 -*-
# www.pythondiario.com
 
from Tkinter import *
from tkMessageBox import *
 
 
def pregunta():
    showerror("Pregunta", "Discuple, no hay preguntas disponibles")
 
 
def devolucion():
    if askyesno('Verificar', '¿Realmente quiere salir?'):
        showwarning('Si', 'No está implementado')
    else:
        showinfo('No', 'Salir fue cancelado')
 
 
Button(text='Salir', command=devolucion).pack(fill=X)
Button(text='Pregunta', command=pregunta).pack(fill=X)
mainloop()

PRACTICA 46 UNIDAD 3: JUEGO DE CARLOS OLVERA




from Tkinter import *  # libreria para utilizar las ventanas,labels,ventanasemergentes y botones
from tkMessageBox import *  # para poder utilizar el abra el cuadro de dialogo
import random  # para poder generar nuneros aleatorios


def funcion(opcion):
    tiposdemanos = ['piedra', 'papel', 'tijera']  # creo un arreglo con tres valores posibles
    eleccion_aleatoria = random.choice(
        tiposdemanos)  # a la variable le asigno un valor a traves de random utilizando uno de los tres valores que estan en el array
    decisioncpu = eleccion_aleatoria  # la variable decision cpu se iguala
    decision_usuario = opcion  # utilizo como parametro la variable opcion y la igualo a decision usuario para poder usarla en el if

    if decision_usuario == 1:  # el numero uno lo uso como tijera y ese valor se lo asigno al presionar el boton 'piedra'
        Decisionusuario = Label(ventana, text='elegiste piedra', font=("agency fb", 12)).place(x=50, y=220)
        imagen1 = PhotoImage(file='piedrausuario.gif')  # utilizo una imagen para mostrar mi seleccion
        lblusuario = Label(ventana, image=imagen1).place(x=50, y=300)  # muestro esa image a traves de un label
        DecisionCPU = Label(ventana, text=('la cpu eligio ' + decisioncpu), font=("agency fb", 12)).place(x=300,
                                                                                                          y=220)  # muestro en pantalla la decision random que genero
        if decisioncpu == "piedra":  # la decision random la comparo con cadenas de caracteres en los 3 casos
            imagen2 = PhotoImage(file='piedracpu.gif')  # eligo la imagen determinada
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)  # y la muestro en pantalla
            showinfo(title='resultado',
                     message='empate')  # atravez de una ventana emergente muestro si gano,perdio o empato

        elif decisioncpu == 'papel':
            imagen2 = PhotoImage(file='papelcpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            showinfo(title='resultado ', message='perdiste')

        else:
            imagen2 = PhotoImage(file='tijeracpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            showinfo(title='resultado', message='Ganaste')



    elif decision_usuario == 2:
        imagen1 = PhotoImage(file='papelusuario.gif')
        lblusuario = Label(ventana, image=imagen1).place(x=50, y=300)
        Label10 = Label(ventana, text='elegiste papel', font=("agency fb", 12)).place(x=50, y=220)
        Label11 = Label(ventana, text=('la cpu eligio ' + decisioncpu), font=("agency fb", 12)).place(x=300, y=220)
        if decisioncpu == 'piedra':
            imagen2 = PhotoImage(file='piedracpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            print 'haz ganado pax'
            showinfo(title='resultado ', message='Ganaste')
        elif decisioncpu == 'papel':
            imagen2 = PhotoImage(file='papelcpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            print 'empate'
            showinfo(title='resultado', message='empate')

        else:
            imagen2 = PhotoImage(file='tijeracpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            print 'haz perdido!!!!'
            showinfo(title='resultado ', message='perdiste')

    elif decision_usuario == 3:
        imagen1 = PhotoImage(file='tijerausuario.gif')
        lblusuario = Label(ventana, image=imagen1).place(x=50, y=300)
        Label10 = Label(ventana, text='elegiste tijera', font=("agency fb", 12)).place(x=50, y=220)
        Label11 = Label(ventana, text=('la cpu eligio ' + decisioncpu), font=("agency fb", 12)).place(x=300, y=220)
        if decisioncpu == 'piedra':
            imagen2 = PhotoImage(file='piedracpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            showinfo(title='resultado ', message='perdiste')
        elif decisioncpu == 'papel':
            imagen2 = PhotoImage(file='papelcpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            showinfo(title='resultado ', message='ganaste')
        else:
            imagen2 = PhotoImage(file='tijeracpu.gif')
            lblcpu = Label(ventana, image=imagen2).place(x=250, y=300)
            showinfo(title='resultado ', message='empate')


ventana = Tk()
ventana.geometry("500x500")
ventana.title('JUEGO DEL PIEDRA PAPEL O TIJERA')

label1 = Label(text="ELIGA UNO DE LOS 3", font=("agency fb", 18)).place(x=10, y=30)

label3 = Label(ventana, text='PIEDRA,PAPEL O TIJERA').place(x=0, y=0)
label2 = Label(ventana, text='un juego clasico y sencillo').place(x=0, y=0)
# boton para piedra
Piedra = Button(ventana, text='piedra', command=lambda: funcion(1)).place(x=50, y=100)
# boton para papel
Papel = Button(ventana, text='papel', command=lambda: funcion(2)).place(x=150, y=100)
# boton para tijera
Tijera1 = Button(ventana, text='tijera', command=lambda: funcion(3)).place(x=250, y=100)

ventana.mainloop()

PRACTICA 45 UNIDAD 3: ADIVINAR NUMERO CON INTERFAZ




from Tkinter import *
from random import *
import random
import tkMessageBox

intentos =0
aux=0

def inicio_jugar():

    arr = [1, 2, 3, 4, 5]
    global intentos
    intentos = random.choice(arr)
    global num
    num = randint(1, 5)

    nom=entrada1.get()

    et1=Label(contenedor,text="Hola "+nom+" estoy pensando en un numero entre 1 y 5, crees poder adivinarlo?",font=("Times New Roman",15)).place(x=0,y=147)
    et2=Label(contenedor,text="La suerte va a decir el numero de intentos que tienes",font=("Times New Roman",15)).place(x=0,y=207)

    et3=Label(contenedor,text="Tienes "+str(intentos)+" intentos",font=("Times New Roman",15)).place(x=90,y=267)
    parte_2()

def parte_2():
    et4 = Label(contenedor, text="Intenta adivinar: ", font=("Times New Roman", 15)).place(x=90, y=337)
    global entrada2
    entrada2= StringVar()
    objentrada2 = Entry(contenedor, textvariable=entrada2).place(x=242, y=342)

    b2 = StringVar()
    b2.set("Verificar respuesta")
    bgame2 = Button(contenedor, textvariable=b2, command=verificar).place(x=380, y=340)

def verificar():
    global aux
    while auxnum:
            tkMessageBox.showinfo("Alerta", "Tu estimacion es muy alta")
            aux+=1
            break

        if num==est:
            accion = tkMessageBox.askyesno("Atencion",
                                           "Haz ganado el juego\n Quieres volver a jugar?")
            if accion == False:
                ventana.destroy()
                break
            else:
                aux = 0
                inicio_jugar()
                break

    if intentos==aux:
        accion = tkMessageBox.askyesno("Atencion","Haz perdido el juego\n Quieres volver a jugar?")
        if accion == False:
            ventana.destroy()
        else:
            aux = 0
            inicio_jugar()

ventana=Tk()
ventana.config(bg="gray")
contenedor=Frame(ventana,width=650,height=650)
contenedor.pack()
t1=Label(contenedor,text="Bienvenido al juego adivina el numero",font=("Times New Roman",15)).place(x=90,y=25)
t2=Label(contenedor,text="Ingresa tu nombre: ",font=("Times New Roman",15)).place(x=90,y=87)


b1=StringVar()
b1.set("Iniciar juego")
bgame=Button(contenedor,textvariable=b1,command=inicio_jugar).place(x=407,y=87)
entrada1=StringVar()
objentrada=Entry(contenedor,textvariable=entrada1).place(x=240,y=90)


ventana.mainloop()

PRACTICA 44 UNIDAD 3: JUEGO DE BLACKJACK





#Librerias
import random
import time

#Variables Globales
global cartas
cartas = ["A",2,3,4,5,6,7,8,9,10,"J","Q","K"]

global nombrejugadores
nombrejugadores = []

#Funciones
def TurnoCartas(nombre):
    total = 0
    eleccion = 1
    i = 1
    deck = []
    print "-Turno de ",nombre,": "

    while (eleccion!=0 & total<21 0="" 11="" 1="" break="" deck.append="" elif="" else:="" i="" if="" ncarta="" numero="" numerosnaturales="[2,3,4,5,6,7,8,9,10]" por="" print="" que="" quieres="" return="" tenga="" time.sleep="" total="" tramposo="" tu="" u="" ue="" valor="">1):
            print "-Total: ", total,"\n"

        if(total<21 0="" 1="" 2="" 3="" 72="" artas:="" blackjack="" carta="" cartas="" deck.append="" deck="" def="" del="" el="" eleccion="0" elif="" else:="" es:="" for="" ganador2j="" ganador="" has="" hecho="" i="" if="" in="" inalizar="" jugador="" l="" mala="" mirar="" n="" nombre="" nombrejugadores.append="" nombrejugadores="" ntroduce="" numero="" numjugadores="" otra="" pedir="" perdido="" print="" range="" respuesta="=2):" return="" suerte="" time.sleep="" total="" turno="" tus="" un="" while="">J2):
        print nombre[0]," Con un Total de ",J1
    elif(J2>J1):
        print nombre[1]," Con un Total de ",J2
    elif(J1==J2):
        print "\nHay un EMPATE!! con un Total de ",J1," en Ambos Jugadores!!"
    else:
        print "\nLos 2 Jugadores PERDIERON!"

def Ganador3J(J1,J2,J3, nombre):
    print "El Ganador es: ",
    time.sleep(3)

    if (J1 > J2 and J1>J3):
        print nombre[0], " Con un Total de ", J1
    elif (J2 > J1 and J2>J3):
            print nombre[1], " Con un Total de ", J2
    elif (J3 > J1 and J3>J2):
            print nombre[2], " Con un Total de ", J3
    elif(J1==J2 and J1!=J3 and J2!=J3):
        print "\nHay un EMPATE!! entre ",nombre[0]," y ",nombre[1]," con un Total de ", J1, " en los Jugadores!!"
    elif (J2 == J3 and J2 != J1 and J3!=J1):
        print "\nHay un EMPATE!! entre ", nombre[1], " y ", nombre[2], " con un Total de ", J2, " en los Jugadores!!"
    elif (J1 == J3 and J1 != J2 and J3!=J2):
        print "\nHay un EMPATE!! entre ", nombre[0], " y ", nombre[2], " con un Total de ", J1, " en los Jugadores!!"
    elif (J1 == J2 and J2 == J3):
        print "\nHay un EMPATE!! con un Total de ", J1, " en TODOS los Jugadores!!"
    else:
        print "\nLos 3 Jugadores PERDIERON!"

#MAIN
continuar = 1
while continuar != 0:
    print "JUEGO DE BLACK JACK"
    print "-"*72
    numjugadores = input("Numero de Jugadores: 1) 1 Jugador  2) 2 Jugadores  3) 3 Jugadores\n")
    NombreJugadores(numjugadores)

    if(numjugadores==1):

        print "Buenas, Jugadores, Vamos a empezar la Partida de BlackJack"
        time.sleep(4)
        print "Inicia el Jugador numero 1"
        time.sleep(2)
        Jugador1 = TurnoCartas(nombrejugadores[0])
        print "Total del Jugador = ",Jugador1,"\n"
        time.sleep(3)
        continuar = input("\nQuieres Jugar Otra Vez???  1)Si   0)No\n")
        del nombrejugadores[:]
        print "-" * 72

    elif(numjugadores==2):

        print "Buenas, Jugadores, Vamos a empezar la Partida de BlackJack"
        time.sleep(4)
        Jugador1 = 0
        Jugador2 = 0
        for i in range(numjugadores):
            print "Inicia el Jugador numero ",i+1
            time.sleep(2)
            if(i==0):
                Jugador1 = TurnoCartas(nombrejugadores[i])
                print "Turno Finalizado. Espera a tu Oponente...\n"
                time.sleep(3)
                print "-" * 72
            else:
                Jugador2 = TurnoCartas(nombrejugadores[i])
                print "Turno Finalizado.\n"

        time.sleep(2)
        print "Eligiendo Ganador",
        time.sleep(2)
        print ".",
        time.sleep(2)
        print ".",
        time.sleep(2)
        print ".\n"
        time.sleep(2)

        Ganador2J(Jugador1,Jugador2,nombrejugadores)
        #jugadores = {nombrejugadores[0]: Jugador1 , nombrejugadores[1]: Jugador2}
        # print "\nEl Ganador es",
        #time.sleep(3)
        #print max(jugadores, key=jugadores.get), " con un Total de ",max(jugadores.values())
        #time.sleep(3)

        continuar = input("\nQuieres Jugar Otra Vez???  1)Si   0)No\n")
        del nombrejugadores[:]
        print "-" * 72

    elif(numjugadores == 3):
        print "Buenas, Jugadores, Vamos a empezar la Partida de BlackJack"
        time.sleep(4)
        Jugador1 = 0
        Jugador2 = 0
        Jugador3 = 0
        for i in range(numjugadores):
            print "Inicia el Jugador numero ", i + 1
            time.sleep(2)
            if (i == 0):
                Jugador1 = int(TurnoCartas(nombrejugadores[i]))
                print "Turno Finalizado. Espera a tu Oponente...\n"
                time.sleep(3)
                print "-" * 72
            elif(i == 1):
                Jugador2 = int(TurnoCartas(nombrejugadores[i]))
                print "Turno Finalizado. Espera a tu Oponente...\n"
                time.sleep(3)
                print "-" * 72
            else:
                Jugador3 = int(TurnoCartas(nombrejugadores[i]))
                print "Turno Finalizado.\n"

        time.sleep(2)
        print "Eligiendo Ganador",
        time.sleep(2)
        print ".",
        time.sleep(2)
        print ".",
        time.sleep(2)
        print ".\n"
        time.sleep(2)

        Ganador3J(Jugador1, Jugador2, Jugador3, nombrejugadores)
        #jugadores = {nombrejugadores[0]: Jugador1, nombrejugadores[1]: Jugador2, nombrejugadores[2]: Jugador3}
        #print "\nEl Ganador es",
        #time.sleep(3)
        #print max(jugadores, key=jugadores.get), " con un Total de ", max(jugadores.values())
        #time.sleep(3)
        continuar = input("\nQuieres Jugar Otra Vez???  1)Si   0)No\n")
        del nombrejugadores[:]

        print "-" * 72

PRACTICA 43 UNIDAD 3: JUEGO LOTERIA






import os
import random
import threading
from Tkinter import *
import PIL
from PIL import Image, ImageTk
import time
import pygame

"""Variables globales"""
imagen=0
stop=0
dir = os.path.dirname(__file__)
Ccartas=dir+"/Cartas/" #establece la ruta hacia las imagenes de cartas
Csonido=dir+"/Sonidos/" #establece la ruta hacia los sonidos
play=1
"""--------------------------------------------------------"""

def setimagen(nombre,x,y): #carga la imagen
    global imagen #Declaro el uso de una variable global
    img = Image.open(nombre) #cargo la imagen mandada como parametro
    img.thumbnail((x, y), Image.ANTIALIAS) #establezco sus dimensiones y la propiedad antialiasado
    imagen = ImageTk.PhotoImage(img) #la convierto a un formato soportado por los widgets de tkinter
    return imagen #retorno el objeto con la imagen

def play():
    global stop,play,TBoton #Declaro el uso de las variables stop y play
    """play: sirve para controlar la pulsasion del boton, si se pulsa una vez el boton jugar en pantalla deberia iniciar el juego
    pero si se vuelve a pulsar deberia detenerse y dado que se usa el mismo boton para ambas acciones la uso para controlar las acciones
    stop: se usa para controlar el hilo de ejecucion declarado, si stop vale 1 debera terminar el hilo, si vale 0 debera continuar hasta que se le indique"""
    if play==1:
        TBoton.set("Pausar")
        t=threading.Thread(target=hilo)
        t.start()
        stop=0 #El hilo continua con normalidad
        play=0 #La proxima vez que se pulse el boton debera entrar en el else
    else:
        TBoton.set("Jugar")
        play=1 #La proxima vez que se pulse el boton debera entrar en el if
        stop=1 #Se detiene el hilo

def reproducirsonido(nombre):
    pygame.init()
    pygame.mixer.music.load(nombre)
    pygame.mixer.music.play()


def hilo():
    global tiempo, cartas, Limagen,stop,Tetiqueta,spin
    cartas = ["EL GALLO", "EL DIABLITO", "LA DAMA", "EL CATRIN", "EL PARAGUAS", "LA SIRENA", "LA ESCALERA",
              "LA BOTELLA", "EL BARRIL", "EL ARBOL", "EL MELON",
              "EL VALIENTE", "EL GORRITO", "LA MUERTE", "LA PERA", "LA BANDERA", "EL BANDOLON", "EL VIOLINCELLO",
              "LA GARZA", "EL PAJARO", "LA MANO", "LA BOTA",
              "LA LUNA", "EL COTORRO", "EL BORRACHO", "EL NEGRITO", "EL CORAZON", "LA SANDIA", "EL TAMBOR",
              "EL CAMARON", "LAS JARAS", "EL MUSICO", "LA ARANA",
              "EL SOLDADO", "LA ESTRELLA", "EL CAZO", "EL MUNDO", "EL APACHE", "EL NOPAL", "EL ALACRAN", "LA ROSA",
              "LA CALAVERA", "LA CAMPANA", "EL CANTARITO",
              "EL VENADO", "EL SOL", "LA CORONA", "LA CHALUPA", "EL PINO", "EL PESCADO", "LA PALMA", "LA MACETA",
              "EL ARPA", "LA RANA"]

    # tiempo=time*1000
    x = 0
    reproducirsonido(Csonido + "inicio.ogg")
    time.sleep(3)
    while True:
        nombre=str(cartas.index(random.choice(cartas))+1)
        carta = Ccartas + nombre + ".png"
        Limagen.config(image=setimagen(carta,400,400))
        Tetiqueta.set("Salio: "+cartas[int(nombre)-1])
        sonido=Csonido+"s_("+nombre+").ogg"
        reproducirsonido(sonido)
        time.sleep(float(spin.get()))
        x = x + 1
        if stop==1:
            break


ventana=Tk()
ventana.config(bg="gray")
contenedor=Frame(ventana,width=700,height=700)
contenedor.pack()
Etitulo=Label(contenedor,text="Loteria Mexicana",font=("Arial",40,"bold")).place(x=120,y=20)
Etiempo=Label(contenedor,text="Tiempo entre cartas: ",font=("Arial",12,"bold"))
Etiempo.place(x=130,y=100)
spin=Spinbox(contenedor,values=[2,3,4,5,6,7,8,9,10,11,12],font=("Arial",12,"bold"))
spin.place(x=295,y=101)
Limagen=Label(contenedor)
Limagen.place(x=300,y=180)

TBoton=StringVar()
TBoton.set("Jugar")
Bplay=Button(contenedor,textvariable=TBoton,command=play)
Bplay.place(x=500,y=98)

Tetiqueta=StringVar()
Enombre=Label(contenedor,textvariable=Tetiqueta,font=("Arial",40,"bold"))
Enombre.place(x=80,y=400)
pygame.init()
ventana.mainloop()

PRACTICA 42 UNIDAD 3: JUEGO DE ALEJANDRO





Código explicado


from random import *
import random
import time
import textwrap

"""manda un mensaje incial"""
msg = ("El siguiente juego consiste en adivinar el numero en que esta pensando la computadora"
       " es importante mencionar que el numero de intentos se establece conforme a la suerte"
       " en el caso de que menciones un numero por debajo del que se busca aparece un mensaje"
       " diciendo que tu estimacion es muy baja, de igual manera sucede en sentido contrario"
       " solo que aparece un mensaje diciendo que la estimacion es muy alta"
       " si llegas a agotar el numero de intentos pierdes el juego, y si lo deseas puedes volver a jugar mucha suerte")

print(textwrap.fill(msg, width = 70)) #Manda a llamar la variable msg y lo imprime. Width sirve para la manera en que el texto se acomodara
print("\nBienvenido al juego adivina el numero")
n=raw_input ("Ingresa tu nombre: ")

back=1
while back==1:
    linea_punteada = 70 * '-'
    print(linea_punteada) #Imprime la linea 70 veces

    print(n+" estoy pensando en un numero entre 1 y 5 " + "crees poder adivinarlo?")
    print("La suerte va a decir el numero de intentos que tienes")
    time.sleep(2)
    print "*"
    time.sleep(2)
    print "**"
    time.sleep(2)
    print "***"

    aux=0
    arr=[1,2,3,4,5]
    intentos=random.choice(arr) #Declara el numero de intentos utilizando random en el arreglo anterior.
    num=randint(1,5)
    print ("Tienes "+str(intentos)+" intentos")


    while auxnum:
            print("Tu estimacion es muy alta")

         elif est==num:
            break
    if num==est:
        print("Good Job "+n+" has adivinado el numero")
    elif num!=est:
        print("Perdiste "+n+" el numero que estaba pensando es:",num)

    print ("Desea volver a jugar? 1.-Si/2.-No") #Da la opcion al jugador si desea volver a jugar o desea terminar
    back=input("Respuesta: ") #El juego seguira siempre y cuando la respuesta resulte ser un 1