I'm trying to import a class from another script so I can run the class when a button is clicked in tkinter.
The line of code I'm trying to run is:
from tkinter import *
import originalscript as desiredclass
variable = desiredclass()
When I try to run my code, the second line gives me an 'invalid syntax' error.
The two files are in the same folder and I've looked at other threads regarding this problem, but most of them suggest this as the solution, however, this line is not working for me, so I'm wondering what I am doing wrong/what I am missing?
The error code is:
Syntax Error: invalid syntax: filepath.py, line 2, pos 10
import script as class
UPDATE:
from you update to your question it looks like you may be trying to import the file as a class. Instead of doing:
variable = desiredclass()
Try this:
variable = desiredclass.ClassNameInFile()
There are several ways you might wish to import your own files.
For example if your file structure looks like this:
--Workfolder
--Main.py
--other.py
You may want to import something like this.
import other
Or if you want only something specific from that file do:
from other import func_name
However if it is part of a package you sometimes need to specify the package name first.
So if your file structure is like this:
--Workfolder
--MY_PACKAGE
--Main.py
--other.py
You may want to import like this:
import MY_PACKAGE.other
or for a specific function:
from MY_PACKAGE.other import func_name
Let me know if you have any questions.
Related
I am here to ask what seems to be a very dumb question, but just cannot find a fix for it. I'm just a beginner and I've also searched StackOverflow for multiple results but such problems are not related to mine. If I've missed one, I'm sorry about that.
my problem is that I'm trying to re-create one of my first console games into an OOP one, but for some reason, I cannot import modules?
firs, I would like to say that I created this on my laptop with Pop os. and that the mentioned two file are the only file on the directory.
so I created a battle_main.py and battle_mechanics.py
on the battle_mechanics.py, it only has the following lines:
class User_Interface:
def __init__(self):
self.player_health = 30
self.squid_health = 30
and on the battle_main.py:
from battle_mechanics import User_Interface
ui = User_Interface()
it's literally just that, yet I cannot import it. it's resulting in ImportError: cannot import name 'User_Interface' from 'battle_mechanics' I know that it's a very simple problem, but I really can't find any fix to it? in fact, I think there's not even a problem in the way I'm importing it. it just wont work. any help is appreciated.
I'm not sure as to why the method your trying isn't working. To the best of my knowledge what your doing already is correct. However one alternative workaround is to put battle_mechanics.py inside a folder package. Include __init__.py inside that folder with the following code:
from .battle_mechanics import *
Then when you use battle_main.py you can use the following import statement.
from package import User_Interface
This should sort out your issue.
I'm trying to import the User class from a file called gui.py into another called snake.py. I want to import the class so that I can use ,a method within the class and an instance of the class called current_user. But when I do:
from gui import User
It imports everything from gui.py. Does anyone know where I've gone wrong and what I can do to fix this?
I'm new to working with multiple files in Python and this is quite confusing to me.
The files for this are available at:
https://github.com/VladRadoi08/Snake-LoginUI
Thanks!
Anything in the file you import will be run. To prevent this, try putting all the code you don't want to run within this conditional:
if __name__ == "__main__":
That will ensure it only runs if you actually run the python file instead of importing it.
I tried writing some commenly used function in a seperate file and import the same into mainApp file, but not able to use import.
I did find many questions regarding the this same question but, the solution was to keep the files in the same folder
I tried without .py as well, but the same error:
Can you please help me how can i fix this issue ?
No '.py'. Just import seperate
Try using this in mainApp.py:
from seperate import *
a()
where seperate.py looks like this:
def a():
print('hi')
Well, sorry, those two files need to be in the same folder. This is not a solution to your problem.
The syntax of a relative import depends on the current location as well as the location of the module, package, or object to be imported. Here are a few examples of relative imports:
from .some_module import some_class
from ..some_package import some_function
from . import some_class
Read more about Absolute vs Relative Imports in Python
In your case it should be:
from .seperate import a
Also check this question:
Importing from a relative path in Python
add your project directory into your path variable so that python know from where you want to import file
I've been working on a project where I have a file which needs to call a function from a file in a sub package/directory, which in turn is calling a function from another file in the same sub package. As such, I have a main file which is importing a sub file. This sub file is also importing another sub file which is in the same package.
The first sub file has no issue whatsoever importing the second sub file. The main file also has no issue importing the first sub file. However, when I put it all together and run the main file, Python thinks that the second sub file doesn't exist, which I find strange. I've simplified and visualised my problem with an example below:
I have the following file hierarchy:
test_package\
__init__.py
main_file.py
test_sub_package\
__init__.py
subfile1.py
subfile2.py
main_file code:
import test_sub_package.subfile1
subfile1 code:
import subfile2
subfile2 code:
def get_string():
return ("Hello, World!")
So, I would expect main_file to import subfile2 via subfile1. However this doesn't seem to be the case because I get an error:
Traceback (most recent call last):
File "...\Test\main_file.py", line 1, in <module>
import test_package.subfile1
File "...\Test\test_sub_package\subfile1.py", line 1, in <module>
import subfile2
ModuleNotFoundError: No module named 'subfile2'
I was a little surprised that I got this error before I even attempted to call the functionality in subfile2. Either way, I'm confused why this doesn't work. Am I just doing something stupid here or am I trying to do something Python fundamentally doesn't support. If anyone can give me a solution it would be most appreciated.
I suspect this is probably a duplicate but I couldn't find an answer to my specific problem. So, sorry in advance.
When you import a module into another module from the same directory you must use must use a relative import in subfile1.py you will need to write:
from . import subfile2
Note, that doesn't give subfile 1 access to get_string to use it in subfile1, you would need to either write subfile2.get_string() or import it directly with:
from .subfile2 import get_string
I have tried this out and it works, I hope this helps :)
Note: that, if you are running a python script, and you need to import a module in that same directory, you can just say import module_name. It makes a difference if it is a script you are running, or a module that is being used in some other script. For a detailed explanation as to why see here
(I assume from your error message that you want to run main.py, if this is not the case you will need to change import test_sub_package.subfile1 to from . import test_sub_package.subfile1)
main file should be:
from test_sub_package.subfile1 import get_string
get_string()
subfile1.py
import test_sub_package.subfile2
I have just started learning python version 3 and trying to create a file in python.
I placed the file in all the places which is shown by this set of command.
import sys
sys.path
The file has a simple function something like this
def hello(var):
print("Hello "+var)
But when I run it
hello("Google")
I am getting NameError.
Please can anybody help me? I am using Windows. Or is it that I have to call by file name and not by function name? If so, how should I call it?
Thanks in advance to whoever helps me.
You need to import your file first:
import myModule
(assuming your file is called myModule.py)
Then you can call the function like this:
myModule.hello('world')
Alternative syntax:
from myModule import hello
hello('world')