Ejercicio 14.- Como ejemplo vamos a realizar un sencillo programa que dibuja un cuadrado en una ventana.
Ejercicio 15.- Realizar un programa que dibuje un polígono de n lados de una determinada longitud para cada lado.
Ahora vamos a crear una función que nos permita dibujar varios polígonos en la misma ventana. Para ello realizarmos el siguiente ejercicio.
Podemos encontrar la documentación oficial de Turtle Graphics en el siguiente enlace:
Ejercicio 18: Obtener una figura dibujando circulos desplazados sucesivamente.
![](https://blogger.googleusercontent.com/img/a/AVvXsEjMq_ArZUc6oeLuXUMoLQcBc0d9b5Hf1tykcMrjWMIJaiEkMLESXpbjGO47FGfeAkiHVuMES3UZ06MybhnSioXYWlmvkCgPumFqFSa1BidlxJnQBf0tLLM2pVQpy4hnqbq9s5jg30yoXITvys1KxxlrDXpP9ULx2ZOysd5_9XsST4PWwZXspcDfUi8hL2LP=w533-h494)
from tkinter import *
from tkinter import ttk
from decimal import Decimal
import sys
root = Tk()
root.config(bd=10) # borde exterior de 15 píxeles, queda mejor
frm=ttk.Frame(root,padding=10)
frm.grid()
def borrar():
n2.set('')
n1.set('')
r.set('')
def salir():
sys.exit()
def sumar():
mensaje()
r.set( float( n1.get() ) + float(n2.get() ) )
def restar():
mensaje()
r.set( float( n1.get() ) - float(n2.get() ) )
def multiplicar():
mensaje()
r.set( float( n1.get() ) * float(n2.get() ) )
def dividir():
mensaje()
if float(n2.get()) > 0: (r.set( float( n1.get() ) / float(n2.get() ) ))
def potencia():
mensaje()
if float(n2.get()) > -1: (r.set( float( n1.get() ) ** float(n2.get() ) ))
def porcentaje():
mensaje()
if float(n2.get()) > -1: (r.set( float( n1.get() ) * float(n2.get())/100))
def mensaje():
res1 = n1.get()
#aquí compruebas que es un número
res1 = float(res1) if res1.isdigit() else n1.set(0)
res2 = n2.get()
#aquí compruebas que es un número
res2 = float(res2) if res2.isdigit() else n2.set(0)
# Estructura del formulario
# Tres StringVar para manejar los números y el resultado
n1=StringVar()
n2=StringVar()
r=StringVar()
result = Label(root,text="")
ttk.Label(root, text="Numero 1").grid(column=0,row=0)
ttk.Entry(root, justify=CENTER, textvariable=n1).grid(column=1,row=0)
#n1 = eval(n1)
ttk.Label(root, text="Numero 2").grid(column=0,row=1)
ttk.Entry(root, justify=CENTER, textvariable=n2).grid(column=1,row=1)
#n2 = eval(n2)
ttk.Label(root, text="Resultado").grid(column=0,row=2)
ttk.Entry(root, justify=CENTER, state=DISABLED, textvariable=r).grid(column=1,row=2)
#r = float(r)
Label(root).grid() # Separador
Button(root, text="Sumar", command=sumar, bg="green").grid(column=0,row=3)
Button(root, text="Restar", command=restar,bg="orange").grid(column=1,row=3)
Button(root, text="Multiplicar", command=multiplicar,bg="cyan").grid(column=2,row=3)
Button(root, text="Dividir", command=dividir,bg="yellow").grid(column=3,row=3)
Button(root, text="Potencia", command=potencia,bg="blue").grid(column=4,row=3)
Button(root, text="Porcentaje", command=porcentaje,bg="magenta").grid(column=5,row=3)
Button(root, text="Borrar", command=borrar).grid(column=6,row=3)
Button(root, text="Salir", command=salir,bg="red").grid(column=7,row=3)
root.title("Mi calculdora")
#root.geometry('450x200')
root.mainloop()
Vamos a crear una sencilla calculadora paso a paso que utiliza varios widget. En primer lugar vamos a crear la ventana con el título y una línea con un cuadro de texto donde aparecerán los resultados del cálculo. Este cuadro de texto se pone en fondo negro y se incializa con un cero en color verde:
from tkinter import *
from tkinter import messagebox
import math
class Mycalc(Frame):
def __init__(self, master, *args, **kwargs):
Frame.__init__(self, master, *args, **kwargs)
self.parent = master
self.grid()
self.createWidgets()
def deleteLastCharacter(self):
textLength = len(self.display.get())
if textLength >= 1:
self.display.delete(textLength - 1, END)
if textLength == 1:
self.replaceText("0")
def replaceText(self, text):
self.display.delete(0, END)
self.display.insert(0, text)
def append(self, text):
actualText = self.display.get()
textLength = len(actualText)
if actualText == "0":
self.replaceText(text)
else:
self.display.insert(textLength, text)
def evaluate(self):
try:
self.replaceText(eval(self.display.get()))
except (SyntaxError, AttributeError):
messagebox.showerror("Error", "Syntax Error")
self.replaceText("0")
except ZeroDivisionError:
messagebox.showerror("Error", "Cannot Divide by 0")
self.replaceText("0")
def containsSigns(self):
operatorList = ["*", "/", "+", "-"]
display = self.display.get()
for c in display:
if c in operatorList:
return True
return False
def changeSign(self):
if self.containsSigns():
self.evaluate()
firstChar = self.display.get()[0]
if firstChar == "0":
pass
elif firstChar == "-":
self.display.delete(0)
else:
self.display.insert(0, "-")
def raiz(self):
self.display.insert(0, "math.sqrt(")
self.append(")")
self.evaluate()
def raizn(self):
self.display.insert(0, "pow(")
self.append(",1/")
def log(self):
self.display.insert(0, "math.log(")
self.append(",10)")
def logn(self):
self.display.insert(0, "math.log(")
self.append(")")
def ex(self):
self.display.insert(0, "math.exp(")
self.append(")")
def pi(self):
self.append("math.pi")
self.evaluate()
def potencia(self):
self.display.insert(0,"(")
self.append(")**")
def porcentaje(self):
self.display.insert(0,"(")
self.append("/100)")
self.evaluate()
self.append("*")
def inverse(self):
self.display.insert(0, "1/(")
self.append(")")
self.evaluate()
def createWidgets(self):
self.display = Entry(self, font=("Arial", 24), relief=RAISED, justify=RIGHT, bg='black', fg='green', borderwidth=0)
self.display.insert(0, "0")
self.display.grid(row=0, column=0, columnspan=5, sticky="nsew")
self.ceButton = Button(self, font=("Arial", 12), fg='red', text="CE", highlightbackground='red', command=lambda: self.replaceText("0"))
self.ceButton.grid(row=1, column=0, sticky="nsew")
self.inverseButton = Button(self, font=("Arial", 12), fg='red', text="1/x", highlightbackground='lightgrey', command=lambda: self.inverse())
self.inverseButton.grid(row=1, column=2, sticky="nsew")
self.delButton = Button(self, font=("Arial", 12), fg='blue', text="Del", highlightbackground='red', command=lambda: self.deleteLastCharacter())
self.delButton.grid(row=1, column=1, sticky="nsew")
self.divButton = Button(self, font=("Arial", 12), fg='red', text="/", highlightbackground='lightgrey', command=lambda: self.append("/"))
self.divButton.grid(row=1, column=3, sticky="nsew")
self.divButton = Button(self, font=("Arial", 12), fg='red', text="(", highlightbackground='lightgrey', command=lambda: self.append("("))
self.divButton.grid(row=1, column=4, sticky="nsew")
self.sevenButton = Button(self, font=("Arial", 12), fg='blue', text="7", highlightbackground='black', command=lambda: self.append("7"))
self.sevenButton.grid(row=2, column=0, sticky="nsew")
self.eightButton = Button(self, font=("Arial", 12), fg='blue', text="8", highlightbackground='black', command=lambda: self.append("8"))
self.eightButton.grid(row=2, column=1, sticky="nsew")
self.nineButton = Button(self, font=("Arial", 12), fg='blue', text="9", highlightbackground='black', command=lambda: self.append("9"))
self.nineButton.grid(row=2, column=2, sticky="nsew")
self.multButton = Button(self, font=("Arial", 12), fg='red', text="*", highlightbackground='lightgrey', command=lambda: self.append("*"))
self.multButton.grid(row=2, column=3, sticky="nsew")
self.divButton = Button(self, font=("Arial", 12), fg='red', text=")", highlightbackground='lightgrey', command=lambda: self.append(")"))
self.divButton.grid(row=2, column=4, sticky="nsew")
self.fourButton = Button(self, font=("Arial", 12), fg='blue', text="4", highlightbackground='black', command=lambda: self.append("4"))
self.fourButton.grid(row=3, column=0, sticky="nsew")
self.fiveButton = Button(self, font=("Arial", 12), fg='blue', text="5", highlightbackground='black', command=lambda: self.append("5"))
self.fiveButton.grid(row=3, column=1, sticky="nsew")
self.sixButton = Button(self, font=("Arial", 12), fg='blue', text="6", highlightbackground='black', command=lambda: self.append("6"))
self.sixButton.grid(row=3, column=2, sticky="nsew")
self.minusButton = Button(self, font=("Arial", 12), fg='red', text="-", highlightbackground='lightgrey', command=lambda: self.append("-"))
self.minusButton.grid(row=3, column=3, sticky="nsew")
self.minusButton = Button(self, font=("Arial", 12), fg='red', text="log", highlightbackground='lightgrey', command=lambda: self.log())
self.minusButton.grid(row=3, column=4, sticky="nsew")
self.oneButton = Button(self, font=("Arial", 12), fg='blue', text="1", highlightbackground='black', command=lambda: self.append("1"))
self.oneButton.grid(row=4, column=0, sticky="nsew")
self.twoButton = Button(self, font=("Arial", 12), fg='blue', text="2", highlightbackground='black', command=lambda: self.append("2"))
self.twoButton.grid(row=4, column=1, sticky="nsew")
self.threeButton = Button(self, font=("Arial", 12), fg='blue', text="3", highlightbackground='black', command=lambda: self.append("3"))
self.threeButton.grid(row=4, column=2, sticky="nsew")
self.plusButton = Button(self, font=("Arial", 12), fg='red', text="+", highlightbackground='lightgrey', command=lambda: self.append("+"))
self.plusButton.grid(row=4, column=3, sticky="nsew")
self.minusButton = Button(self, font=("Arial", 12), fg='red', text="ln", highlightbackground='lightgrey', command=lambda: self.logn())
self.minusButton.grid(row=4, column=4, sticky="nsew")
self.negToggleButton = Button(self, font=("Arial", 12), fg='red', text="+/-", highlightbackground='lightgrey', command=lambda: self.changeSign())
self.negToggleButton.grid(row=5, column=0, sticky="nsew")
self.zeroButton = Button(self, font=("Arial", 12), fg='blue', text="0", highlightbackground='black', command=lambda: self.append("0"))
self.zeroButton.grid(row=5, column=1, sticky="nsew")
self.decimalButton = Button(self, font=("Arial", 12), fg='blue', text=".", highlightbackground='lightgrey', command=lambda: self.append("."))
self.decimalButton.grid(row=5, column=2, sticky="nsew")
self.equalsButton = Button(self, font=("Arial", 12), fg='red', text="=", highlightbackground='lightgrey', command=lambda: self.evaluate())
self.equalsButton.grid(row=5, column=3, sticky="nsew")
self.equalsButton = Button(self, font=("Arial", 12), fg='red', text="e^x", highlightbackground='lightgrey', command=lambda: self.ex())
self.equalsButton.grid(row=5, column=4, sticky="nsew")
self.negToggleButton = Button(self, font=("Arial", 12), fg='red', text="Raiz(2)", highlightbackground='lightgrey', command=lambda: self.raiz())
self.negToggleButton.grid(row=6, column=0, sticky="nsew")
self.negToggleButton = Button(self, font=("Arial", 12), fg='red', text="Potencia", highlightbackground='lightgrey', command=lambda: self.potencia())
self.negToggleButton.grid(row=6, column=1, sticky="nsew")
self.negToggleButton = Button(self, font=("Arial", 12), fg='red', text="Porcentaje", highlightbackground='lightgrey', command=lambda: self.porcentaje())
self.negToggleButton.grid(row=6, column=2, sticky="nsew")
self.negToggleButton = Button(self, font=("Arial", 12), fg='red', text="Raiz(n)", highlightbackground='lightgrey', command=lambda: self.raizn())
self.negToggleButton.grid(row=6, column=3, sticky="nsew")
self.negToggleButton = Button(self, font=("Arial", 12), fg='red', text="Pi", highlightbackground='lightgrey', command=lambda: self.pi())
self.negToggleButton.grid(row=6, column=4, sticky="nsew")
Calculator = Tk()
Calculator.title("Mi calculadora")
Calculator.resizable(False, False)
Calculator.config(cursor="pencil")
root = Mycalc(Calculator).grid()
Calculator.mainloop()