Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I have a problem with importing a function, so far everything worked fine for me until I did the validate function and called it from the button, why am I getting this error?

Main.py
Python
class AplicacionInventario:

    def __init__(self):
        self.root = Tk()
        self.root.title("StockMaster")
        self.root.geometry("400x500")
        #Bloquear agrandar ventana
        self.root.resizable(0,0)

        self.wtotal = self.root.winfo_screenwidth()
        self.htotal = self.root.winfo_screenheight()
        #  Guardamos el largo y alto de la ventana
        self.wventana = 400
        self.hventana = 500
        # #  Aplicamos la siguiente formula para calcular donde debería posicionarse
        self.pwidth = round(self.wtotal/2-self.wventana/2)
        self.pheight = round(self.htotal/2-self.hventana/2)
        #  Se lo aplicamos a la geometría de la ventana
        self.root.geometry(str(self.wventana)+"x"+str(self.hventana)+"+"+str(self.pwidth)+"+"+str(self.pheight))

        self.imagen = Image.open("src/logo.png")
        self.imagen = self.imagen.resize((350, 100))  # Opcional: Redimensionar la imagen
        self.imagen = ImageTk.PhotoImage(self.imagen)
        # Crear un widget Label con la imagen y colocarlo en la ventana
        self.label_imagen = tk.Label(self.root, image=self.imagen)
        self.label_imagen.pack(pady=20)

        #self.login1 = login(self)
        self.prueba = login(self)


        #fetch_data_button = tk.Button(self.root, text="Obtener Datos", command=self.mostrar2)
        #fetch_data_button.pack()
        

        self.root.mainloop()

AplicacionInventario()


loggin.py
Python
def login(self):
        self.t_Email = "Email:"
        self.label_email = tk.Label(self.root, text=self.t_Email)
        self.label_email.pack(pady=5, padx=20)
        self.label_email.place(x=150, y=150, width=100, height=20)
        
        self.entry_email = tk.Entry(self.root)
        self.entry_email.pack(pady=5)
        self.entry_email.place(x=75, y=170, width=250, height=50)
        
        self.t_Password = "Contraseña:"
        self.label_password = tk.Label(self.root, text=self.t_Password)
        self.label_password.pack(pady=5, padx=20)
        self.label_password.place(x=150, y=220, width=100, height=20)
        
        self.entry_password = tk.Entry(self.root, show="*")
        self.entry_password.pack(pady=5)
        self.entry_password.place(x=75, y=240, width=250, height=50)
        
        self.login_email = self.entry_email.get()
        self.login_password = self.entry_password.get()
        
        self.boton_login = tk.Button(self.root, text="Iniciar Sesión", command=self.validar)
        self.boton_login.pack(pady=5)
        self.boton_login.place(x=125, y=300, width=150, height=50)

def validar(self):
    self.conexion_login = connect_to_database()
    self.cursor_conexion_login = self.conexion_login.cursor()

    self.cursor_conexion_login.execute("SELECT email, password FROM usuarios WHERE email=%s AND password=%s", (self.login_email, self.login_password))
    self.verificar_login = self.cursor_conexion_login.fetchone()



ERROR:

Python
Traceback (most recent call last):
  File "/Users/tomassanchezgarcia/Desktop/python-test/main.py", line 64, in <module>
    AplicacionInventario()
  File "/Users/tomassanchezgarcia/Desktop/python-test/main.py", line 38, in __init__
    self.prueba = login(self)
                  ^^^^^^^^^^^
  File "/Users/tomassanchezgarcia/Desktop/python-test/iniciar_sesion.py", line 31, in login
    self.boton_login = tk.Button(self.root, text="Iniciar Sesión", command=self.validar)
                                                                           ^^^^^^^^^^^^
AttributeError: 'AplicacionInventario' object has no attribute 'validar'


What I have tried:

Hello, I have a problem with importing a function, so far everything worked fine for me until I did the validate function and called it from the button, why am I getting this error?

how can I solve that?

Any additional information would be appreciated.
Posted
Updated 31-Jul-23 4:10am
v3

Richard is spot on with his solution, to make for easier reading, I gave you some sample code below. Tweak it to work for your scenario.

The error occurs because the 'validar' function is defined inside the 'login' function, and it is not accessible from outside that scope. To fix the issue, you should define the 'validar' function within the 'login' class and make sure it is indented correctly to be part of the class -

Main.py -
Python
from tkinter import Tk, Image, ImageTk
import tkinter as tk
from loggin import Login

class AplicacionInventario:

    def __init__(self):
        self.root = Tk()
        self.root.title("StockMaster")
        self.root.geometry("400x500")
        self.root.resizable(0, 0)

        #Rest of your code...

        self.login1 = Login(self)

        self.root.mainloop()

AplicacionInventario()


loggin.py -
Python
import tkinter as tk

class Login:
    def __init__(self, app):
        self.app = app

        self.t_Email = "Email:"
        self.label_email = tk.Label(self.app.root, text=self.t_Email)
        #Rest of your code...

        self.boton_login = tk.Button(self.app.root, text="Iniciar Sesión", command=self.validar)
        #Rest of your code...

    def validar(self):
        self.login_email = self.entry_email.get()
        self.login_password = self.entry_password.get()

        self.conexion_login = connect_to_database()
        self.cursor_conexion_login = self.conexion_login.cursor()

        self.cursor_conexion_login.execute("SELECT email, password FROM usuarios WHERE email=%s AND password=%s", (self.login_email, self.login_password))
        self.verificar_login = self.cursor_conexion_login.fetchone()

#Your connect_to_database function here if it's not defined elsewhere...

def connect_to_database():
    #Replace this with your actual database connection code
    pass
 
Share this answer
 
v2
Comments
Tomas Sanchez Garcia 31-Jul-23 12:30pm    
Hola, gracias a todos por vuestra ayuda. Ahora funciona y he logrado entender la lógica.

Ahora tengo esto así en la clase de inicio de sesión:
self.label_email = tk.Label(text=self.t_Email)

y antes era así:
self.label_email = tk.Label(self.root, text=self.t_Email)

¿Por qué tuve que eliminar el "self.root"? Me dio un error si lo puse.

¿La función ya detecta que esas etiquetas y entradas van en la ventana raíz?
Andre Oosthuizen 1-Aug-23 4:17am    
English only please
The code in login.py is not part of a class, so the validar function cannot be accessed by the self reference, as it only refers to the AplicacionInventario object. You should make the login functions part of their own class, or add them to the AplicacionInventario class.
 
Share this answer
 
Comments
Tomas Sanchez Garcia 31-Jul-23 5:30am    
Thank you very much for your answer, but how could I make the validate function part of the login function? Forgive my ignorance but I got a little stuck in this part.

thank you
Richard MacCutchan 31-Jul-23 5:47am    
You need to redesign the login.py module. As it stands it is not part of the AplicacionInventario class, so it should not be using the self references. You should probably create a new class that does the login work, and either pass it a reference to the main window, or let it create its own dialog style window to do the login work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900