1

Me gustaría mucho se me pueden ayudar ya que es de mucha importancia he investigado y no he podido encontrar una respuesta

#Importar libreria de Tkinter para realizar el entono grafico
import tkinter as tki
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

def listas():

    global listaUsuarios
    global listaContrasenas
    global listaTipo

    listaUsuarios=["Admin", "Cliente", "Asistente"]
    listaContrasenas=["Admin", "Cliente", "Asistente"]
    listaTipo=["Administrador", "Asistente", "Cliente"]

def validacion_inicioSesion():

    listas()

    if texto1.get()==listaUsuarios[0] and texto2.get()==listaContrasenas[0]:
        ventana_administrador()
    elif texto1.get()==listaUsuarios[2] and texto2.get()==listaContrasenas[2]:
        ventana_asistente()
    elif texto1.get()==listaUsuarios[1] and texto2.get()==listaContrasenas[1]:
        ventana_cliente()
    elif texto1.get()=="" and texto2.get()=="":
        messagebox.showwarning("Advertencia", "Debe de ingresar un Usuario o Contraseña")
    else:
        messagebox.showerror("Error","Usuario y Contraseña Ingresados Incorrectamente")

def guardar_datos_crear():

    if texto3.get() == "" and texto4.get() == "" and listadesplegable.get()=="":
        messagebox.showerror("Error", "No se han ingresado Datos")
    else:
        messagebox.showinfo("Confirmación", "Datos Guardados Correctamente")
        agregar_a_listas_crear()

def guardar_datos_modificar():

    if texto5.get() == "" and texto6.get() == "":
        messagebox.showerror("Error", "No se han ingresado Datos")
    else:
        messagebox.showinfo("Confirmación", "Datos Guardados Correctamente")


def agregar_a_listas_crear():

    u = texto3.get()
    c = texto4.get()
    t = listadesplegable.get()

    listas()

    listaTipo.append(t)
    listaContrasenas.append(c)
    listaUsuarios.append(u)

    print(listaTipo)
    print(listaUsuarios)
    print(listaContrasenas)

def agregar_a_listas_modificar():

    u = texto5.get()
    c = texto6.get()
    t = listadesplegable.get()

    listas()

    listaTipo.append(t)
    listaContrasenas.append(c)
    listaUsuarios.append(u)

    print(listaUsuarios)
    print(listaContrasenas)
    print(listaTipo)

def ventana_administrador():

    global ventanaAdministrador

    ventanaLogin.destroy()
    ventanaAdministrador = tki.Tk()
    ventanaAdministrador.geometry("900x600")
    ventanaAdministrador.resizable(False, False)
    ventanaAdministrador.title("USUARIO ADMINISTRADOR")
    ventanaAdministrador.configure(bg="Gray")
    ventanaAdministrador.iconbitmap("HBS.ico")

    titulo1 = Label(ventanaAdministrador, text="ADMINISTRADOR",  bg="Black", fg="Orange", font=("Arial", 14))
    titulo1.place(x=0, y=545, height=35, width=900)

    menu1 = Menu(ventanaAdministrador)
    ventanaAdministrador.config(menu=menu1)
    menu1_1 = Menu(menu1, tearoff=0)
    menu1_2 = Menu(menu1, tearoff=0)
    menu1_3 = Menu(menu1, tearoff=0)
    menu1_4 = Menu(menu1, tearoff=0)
    menu1_5 = Menu(menu1, tearoff=0)
    menu1_6 = Menu(menu1, tearoff=0)

    menu1.add_cascade(label="Usuarios", menu=menu1_1)
    menu1.add_cascade(label="Personal", menu=menu1_2)
    menu1.add_cascade(label="Vehículos", menu=menu1_3)
    menu1.add_cascade(label="Alquileres", menu=menu1_4)
    menu1.add_cascade(label="Reportes", menu=menu1_5)
    menu1.add_cascade(label="Acerca de", menu=menu1_6)

    menu1_1.add_cascade(label="Crear", command=ventana_crear)
    menu1_1.add_separator()
    menu1_1.add_cascade(label="Modificar", command=ventana_modificar)

    ventanaAdministrador.mainloop()


def ventana_asistente():

    ventanaLogin.destroy()
    ventanaAsistente = tki.Tk()
    ventanaAsistente.geometry("900x600")
    ventanaAsistente.resizable(False, False)
    ventanaAsistente.title("USUARIO ASISTENTE")
    ventanaAsistente.configure(bg="Gray")
    ventanaAsistente.iconbitmap("HBS.ico")

    titulo1 = Label(ventanaAsistente, text="ASISTENTE", bg="Black", fg="Orange", font=("Arial", 14))
    titulo1.place(x=0, y=545, height=35, width=900)

    menu1 = Menu(ventanaAsistente)
    ventanaAsistente.config(menu=menu1)

    menu1_3 = Menu(menu1, tearoff=0)
    menu1_4 = Menu(menu1, tearoff=0)
    menu1_5 = Menu(menu1, tearoff=0)
    menu1_6 = Menu(menu1, tearoff=0)

    menu1.add_cascade(label="Vehículos", menu=menu1_3)
    menu1.add_cascade(label="Alquileres", menu=menu1_4)
    menu1.add_cascade(label="Reportes", menu=menu1_5)
    menu1.add_cascade(label="Acerca de", menu=menu1_6)

    #menu1_1.add_cascade(label="Crear")
    #menu1_1.add_separator()
    #menu1_1.add_cascade(label="Modificar")

    ventanaAsistente.mainloop()

def ventana_cliente():

    ventanaLogin.destroy()
    ventanaCliente = tki.Tk()
    ventanaCliente.geometry("900x600")
    ventanaCliente.resizable(False, False)
    ventanaCliente.title("USUARIO CLIENTE")
    ventanaCliente.configure(bg="Gray")
    ventanaCliente.iconbitmap("HBS.ico")

    titulo1 = Label(ventanaCliente, text="CLIENTE", bg="Black", fg="Orange", font=("Arial", 14))
    titulo1.place(x=0, y=545, height=35, width=900)

    menu1 = Menu(ventanaCliente)
    ventanaCliente.config(menu=menu1)

    menu1_4 = Menu(menu1, tearoff=0)
    menu1_6 = Menu(menu1, tearoff=0)

    menu1.add_cascade(label="Alquileres", menu=menu1_4)
    menu1.add_cascade(label="Acerca de", menu=menu1_6)

    ventanaCliente.mainloop()

def ventana_crear():

    global texto3
    global texto4
    global listadesplegable

    ventanaCrear = tki.Tk()
    ventanaCrear.geometry("600x400")
    ventanaCrear.resizable(False, False)
    ventanaCrear.title("CREAR USUARIOS")
    ventanaCrear.configure(bg="Gray")
    ventanaCrear.iconbitmap("HBS.ico")

    titulo = Label(ventanaCrear, text="Usuario: ", fg= "Orange", bg="Black", font=("Arial", 12))
    titulo.place(x=15, y=10, height=30, width=150)

    texto3 = tki.StringVar()
    texto4 = tki.StringVar()

    campotexto1 = Entry(ventanaCrear, textvariable=texto3)
    campotexto1.place(x=180, y=10, height=30, width=200)

    titulo1=Label(ventanaCrear, text="Contraseña: ", fg= "Orange", bg="Black", font=("Arial", 12))
    titulo1.place(x=15, y=60, height=30, width=150)

    campotexto2 = Entry(ventanaCrear, textvariable=texto4)
    campotexto2.place(x=180, y=60, height=30, width=200)

    titulo2= Label(ventanaCrear, text="Tipo de Usuario", fg= "Orange", bg="Black", font=("Arial", 12))
    titulo2.place(x=15, y=110, height=30, width=150)

    listadesplegable = ttk.Combobox(ventanaCrear)
    listadesplegable["values"]=("Administrador", "Asistente", "Cliente")
    listadesplegable.place(x=180, y=110, height=30, width=200)

    boton = Button(ventanaCrear, text="Guardar", height=2, width=12, bg="Black", fg="White", font=("Arial", 12), command=guardar_datos_crear)
    boton.place(x=100, y=170, height=30, width=200)

    boton1 = Button(ventanaCrear, text="Cerrar Ventana", height=2, width=12, bg="Black", fg="White", font=("Arial", 12), command=ventanaCrear.destroy)
    boton1.place(x=100, y=250, height=30, width=200)

    ventanaCrear.mainloop()

def ventana_modificar():

    global listadesplegable1
    global texto5
    global texto6

    ventanaModificar = tki.Tk()
    ventanaModificar.geometry("400x250")
    ventanaModificar.resizable(False, False)
    ventanaModificar.title("MODIFICAR USUARIOS")
    ventanaModificar.configure(bg="Gray")
    ventanaModificar.iconbitmap("HBS.ico")

    listadesplegable1 = ttk.Combobox(ventanaModificar)
    listadesplegable1.place(x=180, y=10, height=30, width=200)

    titulo = Label(ventanaModificar, text="Usuarios Disponibles", fg= "Orange", bg="Black", font=("Arial", 12))
    titulo.place(x=15, y=10, height=30, width=150)

    texto5 = StringVar()
    texto6 = StringVar()

    campotexto1 = Entry(ventanaModificar, textvariable=texto5)
    campotexto1.place(x=180, y=60, height=30, width=200)

    titulo1= Label(ventanaModificar, text="Usuario: ",  fg= "Orange", bg="Black", font=("Arial", 12))
    titulo1.place(x=15, y=60, height=30, width=150)

    campotexto2 = Entry(ventanaModificar, textvariable= texto6)
    campotexto2.place(x=180, y=110, height=30, width=200)

    titulo2= Label(ventanaModificar, text="Contraseña:", fg= "Orange", bg="Black", font=("Arial", 12))
    titulo2.place(x=15, y=110, height=30, width=150)

    listadesplegable = ttk.Combobox(ventanaModificar)
    listadesplegable["values"] = ("Administrador", "Asistente", "Cliente")
    listadesplegable.place(x=180, y=160, height=30, width=200)

    titulo3 = Label(ventanaModificar, text="Tipos de Usuario", fg="Orange", bg="Black", font=("Arial", 12))
    titulo3.place(x=15, y=160, height=30, width=150)

    boton = Button(ventanaModificar, text="Guardar", height=2, width=12, bg="Black", fg="White", font=("Arial", 12), command=guardar_datos_modificar)
    boton.place(x=100, y=200, height=30, width=230)

    ventanaModificar.mainloop()

def ventana_login():

    global ventanaLogin

    ventanaLogin = tki.Tk()
    ventanaLogin.geometry("400x480")
    ventanaLogin.resizable(False, False)
    ventanaLogin.title("INICIO DE SESIÓN")
    ventanaLogin.configure(bg="Gray")
    ventanaLogin.iconbitmap("HBS.ico")

    titulo1 = Label(ventanaLogin, text="INICIAR SESIÓN", height=2, width=800, bg="Black", fg="Orange",font=("Arial", 18))
    titulo1.pack()

    imagen=PhotoImage(file="hbs.png")
    imagen=imagen.subsample(2, 2)

    titulo = Label(image=imagen, bg="Gray")
    titulo.pack()

    titulo2 = Label(ventanaLogin, text="USUARIO", bg="Black", fg="Orange", font=("Arial", 18))
    titulo2.place(x=0, y=218, height=50, width=400)

    global texto1
    global texto2

    texto1 = StringVar()
    texto2 = StringVar()

    campotexto1 = Entry(ventanaLogin, textvariable=texto1)
    campotexto1.place(x=100, y=275, height=30, width=200)

    titulo3 = Label(ventanaLogin, text="CONTRASEÑA", bg="Black", fg="Orange", font=("Arial", 18))
    titulo3.place(x=0, y=315, height=50, width=400)

    campotexto2 = Entry(ventanaLogin, show="*", textvariable=texto2)
    campotexto2.place(x=100, y=375, height=30, width=200,)

    boton1 = Button(ventanaLogin, text= "Iniciar Sesión",bg="Black", fg="White", font=("Arial", 12), command=validacion_inicioSesion)
    boton1.place(x=100, y=425, height=30, width=200)

    ventanaLogin.mainloop()

#Programa Principal
ventana_login()
2
  • 2
    Bienvenido a SO, @randy-corea-g El código que has añadido es enorme y resulta costoso analizar lo que pueda estar fallando. Deberías concretar más qué parte del código falla y que sea ilustratriva del problema. Por favor, revisa la ayuda sobre Cómo crear un ejemplo mínimo, completo y verificable. el 10 ago. 2020 a las 22:14
  • ¿En realidad es necesario publicar tanto código para exponer tu problema?
    – jachguate
    el 11 ago. 2020 a las 4:57

1 respuesta 1

1

Randy, tu respuesta se puede solucionar colocando variables globales también a los Entry campotexto1 y campotexto2 (solamente tomando en cuenta la función ventana_crear())

Sería algo así:

def ventana_crear():

    global texto3
    global texto4
    global campotexto1
    global campotexto2
    global listadesplegable

Y en la función agregar_a_listas_crear() la modificaría así:

def agregar_a_listas_crear():

#   u = texto3.get()
#   c = texto4.get()
    u = campotexto1.get()
    c = campotexto2.get()
    t = listadesplegable.get()

    #listas()

    listaTipo.append(t)
    listaContrasenas.append(c)
    listaUsuarios.append(u)

    print(listaTipo)
    print(listaUsuarios)
    print(listaContrasenas)

Con eso ya el código funciona para agregar usuarios... Sin embargo!! no es la forma más elegante y personalmente no soy tan amante de las variables globales.

Lo ideal sería pasar parámetros a la función agregar_a_listas_crear() desde el comando del botón guardar de la función ventana_crear() a través de la función lambda..

Con este paso estamos eliminando la función guardar_datos_crear() ya que no tiene sentido. La validación de los if's ahora pasan a agregar_a_listas_crear()

Sería algo así:

En la función def ventana_crear(): modifico el comando del botón guardar con la función labda:

boton = Button(ventanaCrear, text="Guardar", height=2, width=12, bg="Black", fg="White", font=("Arial", 12),
 command=lambda:agregar_a_listas_crear(campotexto1.get(),campotexto2.get(),listadesplegable.get()))

Y la función agregar_a_listas_crear() quedaría así:

def agregar_a_listas_crear(u, c, t): # Agrego los parámetros que vienen del botón

    if u == "" and c == "" and t == "":
        messagebox.showerror("Error", "No se han ingresado Datos")
    else:
        messagebox.showinfo("Confirmación", "Datos Guardados Correctamente")
        listaTipo.append(t)
        listaContrasenas.append(c)
        listaUsuarios.append(u)
        print(listaTipo)
        print(listaUsuarios)
        print(listaContrasenas)

Si te fijas, el uso de parámetros ayudan a que tu código esté limpio y legible...

Realiza las validaciones y cualquier cosa nos comentas de nuevo

4
  • Es correcto amigo es que eso lo que trato de buscar, que el código se vea los más limpio posible, pero en la parte de trabajar con entorno grafico soy nuevo por ende buscaba en poco de ayuda, además de que apenas llevo 2 meses programando en este lenguaje el 11 ago. 2020 a las 21:58
  • Más bien te agradezco mucho tu ayuda. el 11 ago. 2020 a las 21:59
  • Voy a realizar los cambios que me comentas, lo pruebo te digo si me funciona el 11 ago. 2020 a las 22:02
  • @RandyCoreaG marcar mi respuesta como aceptada, es la mejor forma de agradecer en la comunidad... Quedo atento a cualquier otra inquietud el 12 ago. 2020 a las 3:31

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.