I am a beginner to Eclipse neon + Pydev combo. Trying to use python modules I created into other modules I will be creating. For a start, I was going to use TKinter tutorial program outlined here: http://effbot.org/tkinterbook/tkinter-hello-again.htm
In addition to printing a statement in response to a mouse click, I want to run a small module, fibo.py
Here's my code:
import the library
from tkinter import *
import fibo
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(
frame, text="QUIT", fg="red", command=frame.quit
)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello",command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
fib(100)
print ("hi there, everyone!")
root = Tk()
app = App(root)
root.mainloop()
root.destroy() # optional; see description below
Here's fibo.py
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print (b, end=" ")
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Both modules are in the same project and workspace. The editor says,"unresolved import fibo" Why is the module fibo not recognized by in pydev/eclipse?
My ultimate goal is to run a module upon button click. If there's a more direct way to accomplish this, I would like to know.
Ok, so, based on your screenshot, the structure you have is actually:
/project (this is the PYTHONPATH root and marked as source folder)
/project/root
/project/root/__init__.py
/project/root/nested
/project/root/nested/__init__.py
/project/root/nested/example.py
/project/root/nested/fibo.py
In this case, your import should be: from root.nested import fibo
. Your code may work in the command line, but that's because you added an entry to sys.path
only in runtime (so, PyDev can't follow that).
The other option would be moving both example.py and fibo.py to /project
.
You can also use a relative import as from . import fibo
, but then, to run the module as a __main__
module, you'll have to run modules by the module name (with the -m
flag) -- you can configure PyDev to do that at the preferences > PyDev > Run > Launch modules with "python -m mod.name"
.
As a note, if you just write:
fibo
in your case, and wait for the undefined variable error to be shown, you can use Ctrl+1 in that same line to get a suggestion which will write the import for you (or you can do a code-completion which will also write an import for you automatically).