martes, 27 de noviembre de 2018

Unidad 4: Triangulo y cubo en 3D

Sintaxos del programa 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()

Corrida del programa:



Sintaxis del programa del cubo:


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


Corrida del programa:


domingo, 25 de noviembre de 2018

Unidad 4: Cubo Aniamdo en 3D

Sintaxis del programa:


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

Corrida del programa:


Unidad 4: Graficas de barras en 3D

Sintaxis del programa:


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 = 1
dy = 1
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()

Corrida del programa:


Unidad 4: Interfaz grafica 15 programas.

Programa 1: Signo zodiacal.

Sintaxis del programa:


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

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 Cáncer")
    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 Escorpión")
    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()

Corrida del programa:




Programa 2: Programa que determina si eres mayor de edad.

Sintaxis del programa:


# Ejemplo de Edad con Spinbox.-
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()

Corrida del programa:





Programa 3: Programa que cuenta monedas y billetes


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)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

v9 = ""
v9 = Entry(vp, width=5, textvariable=v9)
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()

Corrida del programa:





Programa 4: Programa que calcula el indice de masa corporal(IMC)

sintaxis:


# -*- 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 desnutrición")

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


Corrida del programa:






Programa 5: Renta de peliculas y agregar peliculas.

Sintaxis:


# 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 it is?", "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 it is?", "Por favor selecciona una clasificacion!")

    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 sera anadida")


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

Corrida del programa:










Programa 6: Captura de datos basicos

Sintaxis:

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)
finish = Button(root,text="finalizar",relief=FLAT)
finish.grid(row=4,column=2)
root.mainloop()

Corrida del programa:


Programa 7: Interes anual

Sintaxis del programa:


# !/usr/bin/env python#
# -*- coding: utf-8 -*-
# programa que calcula el interés anual
 
 
 
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, "años, con un interes de", v2, " usted habrá 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="Años:")
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()

Corrida del programa:




Programa 8: Gif con boton

Sintaxi del programa:


# Programa.- que toma un archivo GIF y lo muestra

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

from Tkinter import *

ventana = Tk()
ventana.geometry('400x400')
ventana.config(bg="lightblue")
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="violet.gif")
b1 = Button(ventana, text="Boton 1", image=imgBoton, fg="pink", width=200)
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()

Corrida del programa:



Programa 9: Calendario

Sintaxis:

#!/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='darkred', 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 ()

Corrida del programa:



Programa 10: Saluda al usuario con el nombre que ingrese.

Sintaxis:

from tkMessageBox import *
from Tkinter import *

def saludos():
    Nombre2 = nombre.get()
    showinfo("Saludador","Saludos "+Nombre2)


ventana = Tk()
frame = Frame(ventana, width=500, height=250)
frame.pack()

ventana.title("Saludador")
label = Label(frame, text="Ingresa un nombre para saludar", font=("Arial", 10, "bold"), fg="blue").place(x=150, y=20)

nombre = StringVar()
Entry = Entry(frame, width=20, textvariable=nombre).place(x=190, y=100)

Nboton = StringVar()
Nboton.set('Saludar')
boton = Button(frame, textvariable=Nboton, command=saludos).place(x=350, y=100)

ventana.mainloop()

Corrida del programa:



Programa 11: Agregar peliculas

from Tkinter import *
from tkMessageBox import *

aux = 0


def agregar_pelicula():
    Seleccion = pelicula.get()
    peliculas.append(Seleccion)
    peliculas_lista = OptionMenu(ventanap, index, *peliculas).place(x=300, y=82)


def quitar_pelicula():
    Seleccion = pelicula.get()
    peliculas.remove(Seleccion)
    peliculas_lista = OptionMenu(ventanap, index, *peliculas).place(x=300, y=82)


ventanap = Tk()
ventanap.geometry("400x250")
ventanap.title("Peliculas")
Label(ventanap, text="Escribe el titulo de una pelicula").place(x=30, y=55)
Label(ventanap, text="Peliculas").place(x=300, y=55)
pelicula = StringVar()
nombre = Entry(ventanap, textvariable=pelicula, width=34).place(x=20, y=90)
peliculas = []
index = StringVar()
#peliculas_lista = OptionMenu(ventanap, index,*peliculas).place(x=300, y=82)
Button(ventanap, text="Agregar", command=agregar_pelicula).place(x=70, y=120)
Button(ventanap, text="Quitar", command=quitar_pelicula).place(x=140, y=120)
ventanap.mainloop()

Corrida del programa:




Programa 12: Programa que muestra la ruta de un programa

Sintaxis:

from Tkinter import *
from tkFileDialog import *


def ruta():
    nombre = askopenfilename()
    Ruta.set(nombre)


root = Tk()
root.geometry("400x200")
Label(root, text="Pulsa el boton y elige una ruta").place(x=50, y=50)
Ruta = StringVar()
Entry(root, textvariable=Ruta, width=42).place(x=50, y=80)
Button(root, text="....", width=5, command=ruta).place(x=320, y=76)

root.mainloop()

Corrida del programa:




Programa 13: Generador de numero al azar

from Tkinter import *
from random import *

def generar_numero():

    if int(variable1.get()) > int(variable2.get()):
        ran = str(randint(int(variable2.get()), int(variable1.get())))
        numero.set(ran)
    elif int(variable1.get()) < int(variable2.get()):
        ran = str(randint(int(variable1.get()), int(variable2.get())))
        numero.set(ran)

ventana = Tk()
ventana.title('Numeros Random')

frame = Frame(ventana, width=250, height=300)
frame.pack()

label1 = Label(frame, text='Numero 1', font=('Arial', 10, 'bold')).place(x=50, y=50)
label2 = Label(frame, text='Numero 2', font=('Arial', 10, 'bold')).place(x=50, y=100)

variable1 = StringVar()
variable2 = StringVar()

spin1 = Spinbox(frame, values=[1,2,3,4,5,6,7,8,9,10], width=10, textvariable=variable1).place(x=150, y=53)
spin2 = Spinbox(frame, values=[1,2,3,4,5,6,7,8,9,10], width=10, textvariable=variable2).place(x=150, y = 103)

label3 = Label(frame, text='Numero Generado', font=('Arial', 10, 'bold')).place(x=20, y=200)

numero = StringVar()
entry = Entry(frame, width=10, textvariable=numero).place(x=150, y=200)

Nboton=StringVar()
Nboton.set('Generar')
Boton = Button(frame, textvariable=Nboton, command=generar_numero).place(x=150, y=250)

ventana.mainloop()

Corrida del programa:

                                               



Programa 14: Encriptar y desencriptar un mensaje

Sintaxis:

# -*- 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("b3", menu_activacion)

# donde mantener el enfoque.
ventana.mainloop()

Corrida del programa:




miércoles, 21 de noviembre de 2018

Ejercicio de interfaz grafica (Practica No. 20)

Sintaxis del programa:


#!/usr/bin/python
# -*- 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='Introduce un valor correcto')

def hacer_click2():
    try:
        _valor = int(entrada_texto2.get())
        _valor = _valor * 10
        etiqueta2.config(text=_valor)
    except ValueError:
        etiqueta2.config(text='Introduce un valor correcto')


def hacer_click3():
    try:
        _valor = int(entrada_texto3.get())
        _valor = _valor * 15
        etiqueta3.config(text=_valor)
    except ValueError:
        etiqueta3.config(text='Introduce un valor correcto')


app = Tk() #Marco de la aplicacion con el objeto Tk()
vp = Frame(app) #Utilizamos el objeto frame

"""Le damos formato a nuestra ventana, y para eso vamos a utilizar el metodo grid el cual nos 
va a permitir posicionarlos elementos graficos en nuestra ventana.

Otro parametro que utilizaremos sera el margen que se define con padx=(50,50) lo cual indica 
50 pixeles del lado derecho y 50 pixeles del lado izquierdo 
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 utilizaremos los metodos columnconfigure() y rowconfigure() los cuales nos van a servir 
para dar un peso relativo al ancho y largo de todos los elementos de 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 1') #Se crea un objeto etiqueta
etiqueta.grid(column=100, row=1)

etiqueta2 = Label(vp, text='Valor 2')
etiqueta2.grid(column=100, row=5)

etiqueta3 = Label(vp, text='Valor 3')
etiqueta3.grid(column=100, row=10)

"""Creamos un boton de ok! y lo posisionamos con grid"""

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

boton2 = Button(vp, text='multiplicar por 10', command=hacer_click2)
boton2.grid(column=1, row=5)

boton3 = Button(vp, text='multiplicar por 15', command=hacer_click3)
boton3.grid(column=1, row=10)


valor1 = ''
entrada_texto = Entry(vp, width=10, textvariable=valor1)
entrada_texto.grid(column=5, row=1)

valor2 = ''
entrada_texto2 = Entry(vp, width=10, textvariable=valor2)
entrada_texto2.grid(column=5, row=5)


valor3 = ''
entrada_texto3 = Entry(vp, width=10, textvariable=valor3)
entrada_texto3.grid(column=5, row=10)
app.mainloop() #Metodo mainloop()

Corrida del programa:





Juego de piedra,papel o tijeras en interfaz grafica. Aporte por Carlos Olvera Magno (Practica No. 19)

Sintaxis del programa:


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),fg='red').place(x=180, y=50)

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

ventana.mainloop()

Corrida del programa:




Juego de numero al azar en interfaz grafica. Aporte por Ivan Gutierrez (Practica No. 18)

Sintaxis del programa:


#!/usr/bin/python
# -*- coding: utf-8 -*-

from Tkinter import *
from random import *
import time
from threading import *
from tkMessageBox import *

play = 1
stop = 0


nombres = ['jugador', 'pequeñuelo', 'pequeño']

nombre = nombres[randint(0, 2)]
num = randint(1, 10)
intentos = randint(3, 5)


def destroy():
    global hilo
    hilo.destroy()
    Ljuego.config(text='')
    Loportunidades.config(text='')

def checar():
    global num, nombre, intentos
    frases = ['Enserio no puedes adivinar?', 'Jajajaja solo eso me faltaba', 'No me ganarás', 'Pobrecito',
              'Aun lo sigues intentando?', 'Creo que ire a dormir en lo que intentas', 'Te crei mas capaz']
    frase = frases[randint(0,6)]
    intentos -=1
    if int(Entry.get())< num:
        showerror("Computadora","Pobresito, una pista, estoy pensando en un numero mas grande")
        Loportunidades.config(text=str(intentos)+" Intentos")
        Ljuego.config(text=frase)
    elif int(Entry.get())>num:
        showerror("Computadora","Uy no "+nombre+" creo que te pasaste")
        Loportunidades.config(text=str(intentos)+" Intentos")
        Ljuego.config(text=frase)


    if int(Entry.get()) == num:
        Loportunidades.config(text='')
        showinfo("Computadora", "Maldicion, Creo que e perdido esta vez, pero la proxima no sera tan facil")
        time.sleep(3)
        sys.exit()
    elif intentos == 0:
        Loportunidades.config(text='')
        showerror("Computadora","Oh oh te has quedado sin intentos")
        Ljuego.config(text="A si que no has podido adivinar \n el numero en el que estaba pensando")
        time.sleep(2)
        Ljuego.config('El nuermo en el que estaba pensando era'+str(num))


def intentos_dialog():
    global intentos, nombre

    if intentos == 3:
        Ljuego.config(text='Veamos como lo haces con 3 intentos ' + nombre)
        Loportunidades.config(text=str(intentos) + ' Intentos')
    elif intentos == 4:
        Ljuego.config(text='Hoy me agarraste de buenas, 4 Intentos!' + nombre)
        Loportunidades.config(text=str(intentos) + ' Intentos')
    elif intentos == 5:
        Ljuego.config(text='Uy, por que no intentas la loteria este dia?\n 5 intentos para ti' +nombre)
        Loportunidades.config(text=str(intentos) + ' Intentos')


def inicio():
    global play, stop
    hilo = Thread(target=juego)
    hilo.start()

def juego():
    global nombre, intentos
    Ljuego.config(text='Hola, soy tu computadora')
    time.sleep(2.5)
    Ljuego.config(text='Listo para jugar?')
    time.sleep(2.5)
    Ljuego.config(text='Cual es tu nombre?')
    time.sleep(1)
    Ljuego.config(text='No me digas, no lo necesito')
    time.sleep(1)
    Ljuego.config(text=('Muy bien '+nombre+' es hora de jugar a adivina el numero'))
    time.sleep(2.5)
    Ljuego.config(text='Estoy pensando en un numero.')
    time.sleep(2.5)
    Ljuego.config(text='No lo se que tal uno entre el 1 y el 10')
    time.sleep(2.5)
    Ljuego.config(text='Ahora viene lo importante, cuantas oportunidades te dare')
    time.sleep(2.5)
    Ljuego.config(text='Veamos, cuantas oportunidades se me da la gana darte')
    time.sleep(2.5)
    Ljuego.config(text='Mmm... que tal')
    time.sleep(3)
    intentos_dialog()
    time.sleep(2.5)
    Ljuego.config(text='Vamos espero y puedas adivinar el numero')
    time.sleep(2.5)
    Ljuego.config(text='Cierto, vas a necesitar esto')
    time.sleep(1)
    Entry.place(x=190, y=400)


ventana = Tk()
ventana.title('Adivina el numero')
ventana.config(bg='gray')


frame = Frame(ventana, width=500, height=500)
frame.pack()

Titulo = Label(frame, text='Bienvenido al juego adivina el numero', font=('Arial', 18, 'bold'), fg='blue')
Titulo.place(x=30, y=30)



Loportunidades = Label(frame, font=("Arial", 10, 'bold'), fg='red')
Loportunidades.place(x=430, y=100)


Ljuego = Label(frame, font=("Arial", 10, 'bold'))
Ljuego.place(x=30, y=100)

NBoton = StringVar()
NBoton.set('Iniciar')
Biniciar = Button(frame, textvariable=NBoton, command=inicio).place(x=300, y=70)

valor = ''
Entry = Entry(frame, width=20, textvariable=valor)
Entry.config(bg='green')

Nboton2 = StringVar()
Nboton2.set('Checar')
Boton = Button(frame, textvariable=Nboton2, command=checar).place(x=350, y=400)

ventana.mainloop()

Corrida del programa:

Al momento de precionar el boton de iniciar, empezara un cambio de labels, haciendo parecer que la misma computadora es la que esta jugando con nosotros, hasta el punto en donde nos dira que esta pensando en un numero entre el 1 y el 10,  y darnos cierta cantidad de intentos entre 3 y 5, y dandonos la caja de texto para poder dar nuestras respuestas.






Unidad 4: Triangulo y cubo en 3D

Sintaxos del programa triangulo 3d: import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * vert...