
Buen día amigos Hivers, este jueves de programación y tecnología, como había mencionado en mi pasada publicación hoy quiero mostrarles este pequeño ejercicio que realice y el cual es muy útil tomarlo como base para hacer algo mas grande o complejo, para aquellos que quisieran colocar en su sitio web una interfaz de calculadora y porque no, quizá estés prestando servicios de delegación, podrías configurar esta calculadora para que conforme un usuario coloque que cantidad de HP te pudiera delegar ver las ganancias que pudiera obtener, en fin como dije esto solo es una mínima base.
Good morning Hivers friends, this Thursday of programming and technology, as I had mentioned in my last post today I want to show you this small exercise that I did and which is very useful to take as a basis to do something bigger or more complex, for those who would like to place a calculator interface on their website and why not, maybe you are providing services of delegation, you could configure this calculator so that as a user enters the amount of HP he could delegate to you, see the profits he could obtain, in short, as I said, this is only a minimum base.
Todo inicia importando tkinter, en la publicación anterior realice un diminuto ejemplo de como tkinter crea la interfaz.

Everything starts by importing tkinter, in the previous post I made a tiny example of how tkinter creates the interface.
Después de importar toda la librería de tkinter, creamos la “ventana”, aquí se puede hacer mucha mas labor, es decir se puede colocar un icono, se pueden colocar medidas especificas de la interfaz, para este ejercicio solo fueron tres factores a tomar en cuenta.

After importing the entire tkinter library, we create the "ventana", here much more work can be done, that is, an icon can be placed, specific measurements of the interface can be placed, for this exercise there were only three factors to take into account bill.
El siguiente elemento es crear la variable de entrada de texto, donde valiendo la redundancia sera la parte del sistema que permitirá la entrada de las operaciones en la interfaz apoyándonos del método GRID, el cual como su nombre lo dice serán acomodados en coordenadas por así decir en una cuadricula.

The next element is to create the text input variable, where, valid for redundancy, it will be the part of the system that will allow the operations to be entered in the interface, relying on the GRID method, which, as its name implies, will be accommodated in coordinates, so to speak. in a grid.
Ahora es el turno de los botones en nuestra calculadora, si bien es la parte que mas pudiera ser tediosa, es copiar y pegar y por ultimo configurar los “botones especiales” eso mas adelante con la creación de funciones para esos botones, entonces debemos de crear los botones (1,2,3,4,5,6,7,8,9,0 / * - + = ( ) . ) como vemos en la siguiente imagen las características de cada botón, es decir boton1 = Button (que estará en “ventana” con el text =”1” y con espaciados de width = 5px y height = 2px) el resto del código lo desglosamos mas adelante.

Now it is the turn of the buttons in our calculator, although it is the part that could be the most tedious, it is to copy and paste and finally configure the "special buttons" that later with the creation of functions for those buttons, then we must create the buttons (1,2,3,4,5,6,7,8,9,0 / * - + = ( ) . ) as we see in the following image the characteristics of each button, that is, boton1 = Button ( which will be in “ventana” with the text =”1” and with width = 5px and height = 2px spacing) the rest of the code will be broken down later.
Ya creados los botones ahora debemos colocarlos en nuestra cuadricula, quedando de la siguiente forma, la idea es darle la forma que vemos en las calculadoras o en el bloque numérico de nuestros teclados, ayudados del método GRID estaremos colocando en columnas y filas, con espacio de 5 pixeles al rededor de cada botón.

Once the buttons have been created, now we must place them in our grid, being as follows, the idea is to give it the form that we see in the calculators or in the numerical block of our keyboards, helped by the GRID method, we will be placing them in columns and rows, with space 5 pixels around each button.
Funciones, ahora si aquí es la parte donde vemos la parte del código de los botones que dice command = Lambda: click_boton(), todos llevarían esta función solo el botón de borra no, posteriormente colocare la función de esa tecla en especifico, esta función aclara donde sera ingresado el texto, pero debemos de tener cuidado ya que debemos de agregar un indice 0, como variable global i = 0, el ¡+ = 1 esta para acomodar de forma correcta los números, de lo contrario todos aparecerán en el indice 0, es decir si ingresamos 123 aparecería como 321.

Functions, now if here is the part where we see the part of the code of the buttons that says command = Lambda: click_boton(), all of them would have this function, only the delete button, no, later I will place the function of that specific key, this function clarifies where the text will be entered, but we must be careful since we must add an index 0, as a global variable i = 0, the ¡+ = 1 is to correctly accommodate the numbers, otherwise they will all appear in the index 0, that is, if we enter 123 it would appear as 321.
Función borrar, como su nombre lo dice esta función borrara lo ingresado en el cuadro de texto y es la que debera de ser ingresada en la tecla borra.

Delete function, as its name says, this function will delete what has been entered in the text box and it is the one that should be entered in the delete key.
Ya casi por terminar tenemos la función que sera el motor de nuestra calculadora y esto es eval() en el enlace pueden ver de formas mas amplia esta función de Python, no creo que sea necesario redundar esta información, esta función, hace que la tarea de evaluar o ejecutar ecuaciones sea mas sencillas, en el enlace hay ejemplo prácticos y creo seria buena idea hacer publicaciones hablando de librerías y funciones en Python que acorten tareas en procesos.

Almost finished we have the function that will be the engine of our calculator and this is eval() in the link you can see this Python function in a broader way, I do not think it is necessary to redound this information, this function makes the task of evaluating or executing equations easier, in the link there are practical examples and I think it would be good idea to make posts talking about Python libraries and functions that shorten tasks into processes.
No olvidemos que debemos colocar ventana.mainloop()
al inicio del ejercicio, creo no ser muy bueno para explicar muy a fondo cada elemento de este código ya que de hacerlo nos detendríamos en cada linea, lo importante de Python es que hay miles de atajos y como hay una comunidad enorme detrás seguro la información simplificada y mejor explicada la encontramos por todos lados, dejo el link de descarga del archivo .py por si alguien se interesa en revisarlo o modificarlo a su antojo, yo aun seguiré trabajando en el, ya que a mi parecer le falta un icono, quizá el efecto Hover en los botones un poco mas de color, sin mas que agregar me despido amigos deseándoles el mejor de sus días, agradeciendo el apoyo a esta y mis otras publicaciones.
Let's not forget that we must place
ventana.mainloop()
at the beginning of the exercise, I think I'm not very good at explaining each element of this code in depth since doing so would stop us at each line, the important thing about Python is that there are thousands of shortcuts and since there is a huge community behind it, we can find simplified and better explained information everywhere, I leave the link to download the .py file in case someone is interested in reviewing it or modifying it at will, I will still continue working on it, since in my opinion it is missing an icon, perhaps the Hover effect on the buttons a little more color, without further ado I say goodbye friends wishing you the best of your days, thanking you for supporting this and my other publications.
Comments (2)
Orale, veo que vas mejorando mucho en tu codigo, felicidades!!, todavia hay forma de hacer que tu codigo sea mas corto, sigue practicando y si tienes dudas, pues preguntame, aunque de python se muy poco
Yay! 🤗
Your content has been boosted with Ecency Points, by @tex73110.
Use Ecency daily to boost your growth on platform!
Support Ecency
Vote for new Proposal
Delegate HP and earn more