Для начала переименуйте ваш файл, если он называется turtle.py
на любое другое адекватное название, далее напишите для примера:
import turtle
print(0)
Если выдаст ответ: 0
— всё работает. Других видимых проблем не существует, turtle
не требует установки, так же при запуске файла, интерпретатор Python-а выдает ошибку, в следующий раз скопируйте ошибку и вставьте в конце, чтобы Вам могли помочь с проблемой.
Все было хорошо. Но в один прекрасный момент я вернулся к коду запустил его и он начал ругаться этой ошибкой.
AttributeError: partially initialized module ‘turtle’ has no attribute ‘Turtle’ (most likely due to a circular import
Сам код банален.
import turtle
t = turtle.Turtle()
t.forward(50)
На обычно IDLE Python все прекрасно работает, но если попробовать запустить файл через IDLE сохраненный в VS то выходит та же ошибка. (Мне удобней писать на VS)
Подскажите где я проглядел?
Спрашивая Google, нашел подобную проблему, но решение было буквально тривиальное изменить название файла с turtle.py на что либо другое. Я изменил, но эффекта 0.
Прошу подсказать в чем моя ошибка.
0 / 0 / 0 Регистрация: 02.07.2016 Сообщений: 5 |
|
1 |
|
Не работает черепашка02.07.2016, 15:59. Показов 26880. Ответов 10
Добрый день! Начала изучать Python по детской книжке. Дошла до графики и столкнулась с проблемой: from turtle import* выдает ошибку, import turtle тоже не работает. Версию python установила, вроде бы, именно для своей операционной системы. Нигде не смогла найти ответ на свой вопрос. Буду очень признательна за помощь. Хочется двигаться дальше. Миниатюры
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
02.07.2016, 15:59 |
Ответы с готовыми решениями: ДП(Черепашка) Черепашка Код модуля: unit SmallTurtle; uses GraphABC; Черепашка Черепашка 10 |
5889 / 3347 / 1033 Регистрация: 03.11.2009 Сообщений: 9,974 |
|
02.07.2016, 17:07 |
2 |
Как Вы устанавливали turtle?
0 |
2740 / 2339 / 620 Регистрация: 19.03.2012 Сообщений: 8,830 |
|
02.07.2016, 17:57 |
3 |
Я кажется знаю в чем проблема. Для проверки зайди в ТЕРМИНАЛ, а не idle, запусти интерпретатор и оттуда импортируй библиотеку. Миниатюры
1 |
5889 / 3347 / 1033 Регистрация: 03.11.2009 Сообщений: 9,974 |
|
02.07.2016, 18:37 |
4 |
думаю вот этот вот turtle.py в /Users/mac/Documents/ ни разу не помогает импортировать turtle)
1 |
0 / 0 / 0 Регистрация: 02.07.2016 Сообщений: 5 |
|
02.07.2016, 20:50 [ТС] |
5 |
Как Вы устанавливали turtle? Боюсь, что никак думаю вот этот вот turtle.py в /Users/mac/Documents/ ни разу не помогает импортировать turtle) Это я просто сохраняла учебный код, чтобы потом запустить программу.
0 |
5889 / 3347 / 1033 Регистрация: 03.11.2009 Сообщений: 9,974 |
|
02.07.2016, 20:54 |
6 |
Не называйте файлы именами модулей, это приводит к весьма неожиданным и я бы даже сказал феерическим результатам
2 |
0 / 0 / 0 Регистрация: 02.07.2016 Сообщений: 5 |
|
02.07.2016, 20:57 [ТС] |
7 |
Спасибо большое! Теперь я знаю, как запустить python из Терминала
0 |
5889 / 3347 / 1033 Регистрация: 03.11.2009 Сообщений: 9,974 |
|
02.07.2016, 20:59 |
8 |
У меня все равно ничего не получилось покажите как именно у ВАс ничего не получилось.
0 |
0 / 0 / 0 Регистрация: 02.07.2016 Сообщений: 5 |
|
02.07.2016, 21:03 [ТС] |
9 |
Окошко терминала и еще одна попытка запустить черепашку в IDLE Миниатюры
0 |
5889 / 3347 / 1033 Регистрация: 03.11.2009 Сообщений: 9,974 |
|
02.07.2016, 21:06 |
10 |
РешениеВ терминале все нормально, в IDLE все та же проблема — вместо того, чтобы импортировать модуль, вы импортируете turtle.py в ~/Documents, потому что Вы назвали его также, как и модуль, а ~/Documents находится в sys.path. Переименуйте файл в my_turtle.py и все станет хорошо.
2 |
0 / 0 / 0 Регистрация: 02.07.2016 Сообщений: 5 |
|
02.07.2016, 21:15 [ТС] |
11 |
Спасибо! Сейчас попробую. Добавлено через 8 минут
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
02.07.2016, 21:15 |
Помогаю со студенческими работами здесь Черепашка Черепашка в визуальном отображение Посоветуйте графическую среду, в которой благодаря коду происходят действия, а-ля черепашка в python… Разработка программы-исполнителя(типа робот, черепашка,роботландия и тд) для младших школьников Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 11 |
In python ModuleNotFoundError: No module named ‘Turtle’ we face this error message when we try to import turtle [small t ] but type Turtle [Capital T ] then the python interpreter shows this error message, If you want to fix this error you need to just remove Turtle [Capital T ] and use turtle [small t ], For more clarification see the below example.
Wrong Code
# Step 1 import and Set the turtle's bg colour and title
import Turtle
turtle.title("Amol Blog Turtle Fractal Tress")
turtle.bgcolor('black')
#Step 2 create a tree branch function
def draw_branch(length, depth):
if depth == 0:
return
# Draw the main branch
turtle.forward(length)
turtle.right(20)
# Draw the right branch
draw_branch(length * 0.8, depth - 1)
turtle.left(40)
# Draw the left branch
draw_branch(length * 0.8, depth - 1)
turtle.right(20)
# Return to the starting position
turtle.backward(length)
#Step 3 set turtle size, colour, speed and more
turtle.pensize(4)
turtle.color('gold')
turtle.left(90)
turtle.speed('fastest')
turtle.penup()
turtle.backward(200)
turtle.pendown()
#Step 4 Create 100c tall with 8 branch of each tree
draw_branch(100, 8)
#Step 5 close the window after clicking
turtle.exitonclick()
Error Massage
Traceback (most recent call last):
File "/home/kali/python/webproject/turtle/fractal_tress/main.py", line 2, in <module>
import Turtle
ModuleNotFoundError: No module named 'Turtle'
Wrong code line
import Turtle
Correct code line
import turtle
- Wrong action: Turtle [Capital T ].
- Correct action: turtle [small t ].
Entire Correct Code line
# Step 1 import and Set the turtle's bg colour and title
import turtle
turtle.title("Amol Blog Turtle Fractal Tress")
turtle.bgcolor('black')
#Step 2 create a tree branch function
def draw_branch(length, depth):
if depth == 0:
return
# Draw the main branch
turtle.forward(length)
turtle.right(20)
# Draw the right branch
draw_branch(length * 0.8, depth - 1)
turtle.left(40)
# Draw the left branch
draw_branch(length * 0.8, depth - 1)
turtle.right(20)
# Return to the starting position
turtle.backward(length)
#Step 3 set turtle size, colour, speed and more
turtle.pensize(4)
turtle.color('gold')
turtle.left(90)
turtle.speed('fastest')
turtle.penup()
turtle.backward(200)
turtle.pendown()
#Step 4 Create 100c tall with 8 branch of each tree
draw_branch(100, 8)
#Step 5 close the window after clicking
turtle.exitonclick()
What is ModuleNotFoundError: No module named ‘Turtle’?
In python, we face this error message when we try to import turtle [small t ] but type Turtle [Capital T ] then the python interpreter shows this error message.
How to fix ModuleNotFoundError: No module named ‘Turtle’?
If you want to fix this error you need to just remove Turtle [Capital T ] and use turtle [small t ], For more clarification see the above example.
For more information Visit Amol Blog Code YouTube Channel.
So for a beginner python course, I needed to install python3 on my Mac (which was running on Python 2.7.x — x meaning some number I can’t recall but I dont think it matters here).
I had a setup installation guide — which was meant for windows though — which included the following steps:
— Install python 3.
— At complete download, tick the Add Python 3.7 to PATH box when it is shown (which it didnt show on my wizard installation on Mac)
— Install PyCharm
— On new project, select Python 3.7 as Base Interpreter
— To check that your installation is successful, go to terminal and type python —version (mine kept being Python 2.7 despite having Python 3 installed).
I figured out the problem was I needed to change the PATH for Python but I am not very comfortable with the terminal and couldnt figure out how to change that — total beginner here.
So I installed Anaconda who did the whole thing for me and then for some reason (total beginner here!) I found myself with two interpreters on PyCharm: Python 3.7 and 3.8.
PyCharm works with both of them. The problem comes when I need to import turtle into Pycharm and it keeps giving me errors. This is the command output:
Collecting turtle
Using cached turtle-0.0.2.tar.gz (11 kB)
ERROR: Command errored out with exit status 1:
command: /Users/xxxxxx/Documents/projects/cfg-python/venv/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/lg/s5jdvb7j5zldn8pd1nfcrn580000gn/T/pycharm-packaging/turtle/setup.py'"'"'; __file__='"'"'/private/var/folders/lg/s5jdvb7j5zldn8pd1nfcrn580000gn/T/pycharm-packaging/turtle/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'rn'"'"', '"'"'n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/lg/s5jdvb7j5zldn8pd1nfcrn580000gn/T/pip-pip-egg-info-crzjvqnl
cwd: /private/var/folders/lg/s5jdvb7j5zldn8pd1nfcrn580000gn/T/pycharm-packaging/turtle/
Complete output (6 lines):
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/lg/s5jdvb7j5zldn8pd1nfcrn580000gn/T/pycharm-packaging/turtle/setup.py", line 40
except ValueError, ve:
^
SyntaxError: invalid syntax
----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
Under «proposed solution» it also says the following: Try to run this command from the system terminal. Make sure that you use the correct version of ‘pip’ installed for your Python interpreter located at ‘/Users/xxxxxx/Documents/projects/cfg-python/venv/bin/python’.
Also if I type pip —version into the terminal it says «pip 20.1 from /opt/anaconda3/lib/python3.7/site-packages/pip (python 3.7)».
I am currently using the latest version of pip (20.1) for Python 3.8 as Project Interpreter — but maybe I need to change it? Problem is when I try to install packaging tools for Python 3.7 PyCharm says «Invalid Python SDK — and as specifics «Cannot run program «/Users/xxxxxx/Desktop/Coding/CFG 2/cfg-python/venv/bin/python» (in directory «/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers»): error=2, No such file or directory» . I have been googling for the past four hours and really can’t seem to figure it out so I hope you guys will for me. Hope I have given you all the necessary info to solve it. Thank you! Ps. Whatever you need to explain, especially involving the terminal, do it like you’re talking to a five year old please