源代码
from turtle import *
setup(800, 800)
pensize(2)
circle(100)
color('red','yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
问题描述
在开发过程,在PyCharm中导入模块时提示经常出现Unresolved Reference问题。
红线并提示Unresovled reference, 虽然运行没有问题,但看着很不舒服。
Unresolved reference 'left' less... (Ctrl+F1)
This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.
问题分析
既然这些类都在工程中,那么import不成功就是因为路径没对应,事实上是pycharm默认该项目的根目录为source目录,所以import使用绝对路径而不是相对路径的话,就会从项目的根目录中查找,而不是我们希望的其中的/src目录,所以import不成功。
解决方案
- 改成相对路径
from ...package import *
第一个'.'表示当前目录,后面的每一个’.’表示上一层目录。用相对目录可以保证import成功,但是不建议这种写法,因为如果当前这个文件要移动到其他包的话,就要改很多地方了,当然,使用相对路径表示可以随意更改包名,只要保证包名和相对路径正确,就可以运行。
- 在pycharm中设置source路径
1. 进入PyCharm->File–>Preferences->Project:Server–>Project Structure;
2. 将放Package的文件夹设置为source,这样import的模块类等,就是通过这些source文件夹作为根路径来查找,也就是在这些source文件夹中查找import的东西;
3. 点击Apply和OK;
4.清除缓存并重启。
参考文章
https://www.cnblogs.com/xiaohuamao/p/6903030.html
https://blog.csdn.net/u014496330/article/details/55211398
http://stackoverflow.com/questions/21236824/unresolved-reference-issue-in-pycharm