0

I've been trying to run this simple test just to get the feel of how to import methods from another script, but I have two problems:

  1. the whole program runs instead of just importing and calling, the methods, when I need them too.

  2. I'm getting this error:

    Traceback (most recent call last):
      File "C:\Users\devilboy 4\Documents\Visual Studio 2013\Projects\classvariablesOnANewScript\classvariablesOnANewScript\classvariablesOnANewScript.py", line 1, in <module>
    from logInScreen import getUser, getPass
    

    ImportError: cannot import name getUser

This is the script I'm importing to:

from logInScreen import getUser, getPass
class hello:

    def show(self):
        usr = getUser()
        ps = getPass()
        str(usr)
        str(ps)

h = hello()
h.show()

This is what's on logInScreen.py :

from tkinter import *
import os
import tkinter.messagebox

#check si lo entrado es correcto
class checkValidation:
    fail = 0
    user = "hi user"
    password = "nice pass"

   #valida el user y el pass
    def fullVali(self, name, passwd):
         if  name == "" or name == " ":
            tkinter.messagebox.showinfo( "Error","Dejo el usuario en blanco")
            self.fail+= 1
        elif name != "UmetSeg":        
            tkinter.messagebox.showinfo( "Error","Usuario incorrecto")
            self.fail+= 1           
        else :
            self.user = name           
            tkinter.messagebox.showinfo( "ok","dude" + name)

        if  passwd == "" or passwd == " ":
            tkinter.messagebox.showinfo( "Error","Dejo la password en blanco")
            self.fail+= 1
        elif passwd != "SegUmet":            
            tkinter.messagebox.showinfo( "Error","Password incorrecto")
            self.fail+= 1            
        else:
            self.password = passwd           
            tkinter.messagebox.showinfo( "ok","dude" + passwd)
            form.destroy()

         #open another py script    
            #os.system("mainPage3.py 1")
            return

 # no deja pasar parametros por command en el boton a menos que se por lambda, so corre       #este metodo para 
 #correr el metodo de validar
    def callVali(self):
        user = usrIn.get()
        self.fullVali(usrIn.get(), passIn.get())
        return

    def getUser(self):
        return self.user

    def getPass(self):
        return self.password



vali = checkValidation()
form = Tk()
form.title("LogIn")
form.geometry("300x320+300+200")

#User txtBox
usrIn = Entry(form, textvariable = None, width = 30)
usrIn.place(x = 60, y = 140)
user = usrIn.get()
#Passwd txtBox
passIn = Entry(form, textvariable = None, width = 30)
passIn.place(x = 60, y = 200)
#Username Label
usrLblVal = StringVar()
usrLblVal.set("User name")
usrLbl = Label(form, textvariable = usrLblVal  )
usrLbl.place(x = 120, y = 115)

#Passwrd label
passLblVal = StringVar()
passLblVal.set("Password")
passLbl = Label(form, textvariable = passLblVal  )
passLbl.place(x = 120, y = 175)


#Login btn
btn = Button(form, text = "Entrar", width = 10, command = vali.callVali)
btn.place(x = 110, y = 250)

form.mainloop()

I hope I got the indentation right, kinda off a pain going through every line and spacing 4 times till it's right. I apologize for the Spanish, just ignore all the comments lol

1
  • Are you aware you can just highlight all of the code, then click on the button that looks like {}? It will automatically add the four spaces for you. Commented Feb 25, 2014 at 21:15

2 Answers 2

4

You are attempting to import methods from within a class in your LogInScreen.py file. The methods getUser and getPass are bound methods that belong to the class checkValidation, You need to instead import the class and make the call on your class instead

from LogInScreen import checkValidation

validation = checkValidation()
validation.getUser()
validation.getPass()

As a simple illustration consider the following example involving two files:

file_to_import_from.py (Analogous to your logInScreen.py)

class MyClass:
    def my_class_bound_method(self):
        print "hello I a method belonging to MyClass"

def my_method_not_belonging_to_a_class():
    print "Hello, I am a method that does not belong to a class"

file_to_import_to.py (Analogous to the script you are importing to)

from file_to_import_from import my_method_not_belonging_to_a_class

my_method_not_belonging_to_a_class()


from file_to_import_from import MyClass

x = MyClass()
x.my_class_bound_method()

from file_to_import_from import my_class_bound_method

my_class_bound_method()

And see Output

Hello, I am a method that does not belong to a class
hello I a method belonging to MyClass

Traceback (most recent call last):
  File "C:\Users\Joe\Desktop\Python\import_test2.py", line 10, in <module>
    from file_to_import_from import my_class_bound_method
ImportError: cannot import name my_class_bound_method

As you can see, the first two calls worked, but the second time the error you are facing arose, this is because the method my_class_bound_method exists as a method within the class MyClass.

EDIT:

In response to your comment, to avoid running the whole file, surround the code in your 'LogInScreen.py' in an if statement which checks if the file being evaluated by the interpreter is the main file being run.

from tkinter import *
import os
import tkinter.messagebox

#check si lo entrado es correcto
class checkValidation:
    # CODE FROM YOUR CLASS OMITTED FOR BREVITY SAKE

# NOTHING BEYOUND THIS IF STATEMENT WILL RUN WHEN THE FILE IS IMPORTED
if __name__ == "__main__":
    vali = checkValidation()
    # MORE CODE OMITTED FOR BREVITY
    form.mainloop()

The if statement I added here checks a special environment variable that python creates when it interprets a file, which is __name__, when the file is the file that you are directly running: python file_i_am_running.py the variable __name__ is set the the string "__main__" to indicate it is the main method, when it is not the file being run, and maybe one being imported as in your case, the variable is set to the module name, i.e. file_to_import.

Sign up to request clarification or add additional context in comments.

5 Comments

that fixed one, but when I import the class the whole program runs. Like the window open and everything is placed. I don't want to run the program. Should I place all of the buttons, entry and labels on a method and maybe that fixes it?
@chelo666 That is due to the nature in which python performs an import. Essentially when you import the whole file, you are asking python to run the file. This solution can be fixed by the note on my edit.
Nice, I get it. Thanks.
is it __name__ with tow underscore or one _name_? Can't really tell
@chelo666 __name__ with two underscores _ _ n a m e _ _ without all that whitespace ;)
0

Change to this:

from logInScreen import checkValidation

And then, use:

check = checkValidation()
usr = check.getUser()
ps = check.getPass()

3 Comments

your example is wrong. You create an instance called check, then call val.getUser(). You should be calling check.getuser().
Thanks, I answered fast.
I prefer using the same variable instead of using more then one. Thanks for the advice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.