Admittedly I am a noob with Python but I know enough to know that something stupid is going on here and I cannot find any help on google. All I want to do is use Tkinter for a simple GUI but it's pretty hard to do that when I get an Import error any time I try to import and use a function from one.
I followed a tutorial for this one with my own naming etc:
#testUI.py
from tkinter import *
from test2 import nameit
root = Tk()
root.title('Scott Window')
root.geometry('500x350')
greet = nameit('John')
mylabel = Label(root, text=greet)
mylabel.pack(pady=20)
root.mainloop()
#test2.py
def nameit(name):
greeting = name
return greeting
Using this yields:
ImportError: cannot import name 'nameit' from 'test2'
The other way that I have tried is using just "import"
from tkinter import *
import test2
root = Tk()
root.title('Scott Window')
root.geometry('500x350')
greet = test2.nameit('John')
mylabel = Label(root, text=greet)
mylabel.pack(pady=20)
root.mainloop()
This yields an error as well:
AttributeError: module 'test2' has no attribute 'nameit'
I am really at a loss as of what to do, again I'm almost positive it's something stupid but I cannot for the life of me find anything on google, on stackoverflow or anywhere else.
10000 Lifetimes of prosperity to anyone who can help me with this. Thank you!
CodePudding user response:
The example you provided worked on my end, however, this problem may be because of some of the imports you are making in your test2.py file.
For example, in testUI.py you are importing test2 and in test2.py you are importing testUI. You need to find away to break this cycle and reduce the dependence.
An example is shown below:
# testUI.py
from tkinter import *
from test2 import nameit
root = Tk()
root.title('Scott Window')
root.geometry('500x350')
greet = nameit('John')
mylabel = Label(root, text=greet)
mylabel.pack(pady=20)
root.mainloop()
# test2.py
import testUI # Extra import statement
def nameit(name):
greeting = name
return greeting
When you run test2.py, you get the desired result.
When you run testUI.py, however, you get the following error:
from test2 import nameit
ImportError: cannot import name 'nameit' from partially initialized module 'test2' (most likely due to a circular import)
