Python - recibir datos de tkinter y hacer operaciones matematicas entre listas paralelas

 
Vista:
Imágen de perfil de Jessica
Val: 2
Ha disminuido su posición en 7 puestos en Python (en relación al último mes)
Gráfica de Python

recibir datos de tkinter y hacer operaciones matematicas entre listas paralelas

Publicado por Jessica (1 intervención) el 03/11/2020 21:25:51
Hola chicos!

He estado trabajando en un programa (lenguaje Python) que debe recibir datos desde una GUI tkinter, para realizar operaciones matemáticas.

El programa se divide en algunas partes. Primero se verá una estructura como una tabla, compuesta por 5 columnas. En realidad, cada columna es un diccionario.

Después de la tabla verás un botón, cuando el usuario haga click en él, activa la función GuardarDatos (), y dentro de este, cada diccionario envía información para hacer una lista, para finalmente intentar hacer algún cálculo matemático entre listas (suma y multiplicar).

Cuales son mis problemas?

Probé muchas formas para hacer la operación matemática entre listas, pero el resultado es como una agrupación de string. En otras palabras, si "suministros [1] = 1" y "mano_obra [1] = 1", y traté de hacer una "suma", el resultado es "11", no el número "2".

Quiero poner el resultado de las operaciones matemáticas en la columna respectiva ("unitario" y "valor total"), pero no puedo usar el "método set".

Agradezceria toda la ayuda que me pudan dar. Gracias! :D

Les dejo mi codigo a continuacion:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
from tkinter import*
from math import *
import operator
 
root = Tk()
root.title("Window")
root.geometry("800x600")
 
labelframe1 = LabelFrame(root, text="Table for operations")
labelframe1.pack()
############################################################################
# ----------------  VARIABLE DECLARATION  ------------------------------
############################################################################
cantidad = []
valor_unitario = []
total_parcial = []
suministros = []
mano_obra = []
 
###################################################################################
# =============================   FUNCTION  ====================================
###################################################################################
 
 
def GuardarDatos():
    for key in entries_suministros:
        suministros.append(entries_suministros[key].get())
        print("suministros: ", suministros)
 
    print("=====================")
 
    for key in entries_mo:
        mano_obra.append(entries_mo[key].get())
        print("mano de obra: ", mano_obra)
    print("=====================")
 
    print("==== unitarios ========")
    valor_unitario = list(map(operator.add, suministros,
                              mano_obra))
 
    print("valor unitario: ", valor_unitario)
 
    print("==== totales parciales ======")
    total_parcial = list(map(operator.mul, valor_unitario,
                             cantidad))
 
    print("totales parciales:", total_parcial)
 
 
########################################################################################
# ANOTHER OPTION TO MAKE MATH OPERATION --- IT DOES NOT WORKED
#######################################################################################
    # def add(suministros, mano_obra):
    # for x in range(0, len(suministros)):
    #    loco = (suministros[x]) + (mano_obra[x])
    #   valor_unitario.append(loco)  # Suma Strings
    # Letrero_unit.config(text=valor_unitario)
    #   print(valor_unitario[x])
    #    return valor_unitario  # Con el returno me pone 1 en posicion "[0]"
####################################################################################
# ======================== TABLE STRUCTURE ===================================
####################################################################################
# COLUMN 1: CANTIDAD =======================
entries_cant = {}
for row0 in range(0, 3):
    datosEntry0 = Label(labelframe1, text="cantidad")  # Label
    datosEntry0.grid(row=0, column=0, sticky="nsew")  # Label
    datosEntry0 = Entry(labelframe1)  # Entry
    datosEntry0.grid(row=row0, column=0)  # Entry
    entries_cant["Entrybox{0}".format(row0)] = datosEntry0  # Entry
 
 
# COLUMN 2: UNITARIOS =================
for row1 in range(3):
    datosEntry1 = Label(labelframe1, text="Unitario")
    datosEntry1.grid(row=0, column=1, sticky="nsew")
    datosEntry1 = Entry(labelframe1)
    datosEntry1.grid(row=row1, column=1)
 
 
# COLUMN 3: TOTALES ===================
for row2 in range(3):
    datosEntry2 = Label(labelframe1, text="Valor Total")
    datosEntry2.grid(row=0, column=2, sticky="nsew")
    datosEntry2 = Entry(labelframe1)
    datosEntry2.grid(row=row2, column=2)
    # total_parcial.append(datosEntry2)
 
 
# COLUMN 4: SUMINISTROS ===================
entries_suministros = {}
for row3 in range(3):
    datosEntry3 = Label(labelframe1, text="Suministros")
    datosEntry3.grid(row=0, column=3, sticky="nsew")
    datosEntry3 = Entry(labelframe1)
    datosEntry3.grid(row=row3, column=3)
    entries_suministros["Entrybox{0}".format(row3)] = datosEntry3  # Entry
 
# COLUMN 5: MANO DE OBRA ===================
entries_mo = {}
for row4 in range(3):
    datosEntry4 = Label(labelframe1, text="Mano de Obra")
    datosEntry4.grid(row=0, column=4, sticky="nsew")
    datosEntry4 = Entry(labelframe1)
    datosEntry4.grid(row=row4, column=4)
    entries_mo["Entrybox{0}".format(row4)] = datosEntry4  # Entry
 
###################################################################################
############ =============  BUTTON  ================== ##########################
# BUTTON 1:  =============================
calcular1 = Button(root, text="Send for Operations", command=GuardarDatos)
calcular1.pack()
 
 
root.mainloop()
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Anikollaste
Val: 570
Bronce
Ha mantenido su posición en Python (en relación al último mes)
Gráfica de Python

recibir datos de tkinter y hacer operaciones matematicas entre listas paralelas

Publicado por Anikollaste (118 intervenciones) el 03/11/2020 22:34:56
Hola jessica.
Este es un fragmento de código de una aplicación mía, espero que te sirva como referencia.(Son varias clases y módulos)
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
def dni(self):
    self.obDni=tk.StringVar() #Variable del Entry donde se almacena el dato string
    #self.obDni=tk.IntVar() # Si quieres que el dato sesa de tipo entero
    lDni=tk.Label(self.miFrame, text='DNI:',bg='#3F3C3C',fg='#04B486')
    lDni.grid(row=0, column=0, sticky='e', pady=5, padx=5)
    # textvariable dónde se va a almacenar el dato
    tDni=tk.Entry(self.miFrame,textvariable=self.obDni,fg='#A34B0C')
    tDni.grid(row=0, column=1, pady=5, padx=5)
 
 
def telefono(self):
    self.obTelefono=tk.StringVar()
    lTel=tk.Label(self.miFrame, text='Teléfono:',bg='#3F3C3C',fg='#04B486')
    lTel.grid(row=0, column=2, sticky='e', pady=5, padx=5)
    tTel=tk.Entry(self.miFrame,textvariable=self.obTelefono,fg='#A34B0C')
    tTel.grid(row=0, column=3,pady=5, padx=5)
 
def datosCliente(self):
    datos_cliente=[
    ['Dni:',self.obDni.get()], #Obtengo el valor asociado a la variabl self.obDni
    ['Télefono:',self.obTelefono.get()],
    ['Apellidos:',self.obApellido.get()],
    ['Nombre:',self.obNombre.get()],
    ['Dirección:',self.obDireccion.get()]
    ]
 
    with open('Datos_Cliente.csv','w',newline='') as f:
        w=csv.writer(f)
        w.writerows(datos_cliente)
Aquí te dejo el repositorio por si te sirve de ayuda.
https://github.com/Anikollaste/GestionPedidosOnline.git
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar