Error when importing function that uses Turtle from a different file

Viewed 137

I just started learning Python. I'm trying to use the turtle module. In the same directory, I have two files, script.py and test.py.

In script.py, I have a function written as follow:

import turtle


def circle(x, y, r, colour)
    turtle.showturtle()
    turtle.shape('classic')
    turtle.penup()
    turtle.setx(x)
    turtle.sety(y)
    turtle.pendown()
    turtle.pencolor(colour)
    turtle.fillcolor(colour)
    turtle.begin_fill()
    turtle.circle(r)
    turtle.end_fill()
    turtle.hideturtle()


circle(100, 100, 100, 'blue')

turtle.mainloop()

running script.py produces the blue circle.

I then want to import script.py to test.py. I did the following:

import script as file2

file2.circle(100, 100, 100, 'red')

*EDIT: I previously mistakenly written this as file2.script(), but it was noted correctly in python.

When I ran test.py without creating a configuration for script.py, without calling circle in script.py, I could draw the circle and edit its variable in test.py.

After i edit and save a configuration (simply using the directory for script.py and let it autofill), the function could not run and I got the following error.

Traceback (most recent call last):
  File "C:\Users\username\PycharmProjects\project2\test.py", line 3, in <module>
    circle.draw_circle(100, 100, 100, 'red')
  File "C:\Users\username\PycharmProjects\project2\script.py", line 5, in circle
    turtle.showturtle()
  File "<string>", line 5, in showturtle
turtle.Terminator

Process finished with exit code 1

I can't seem to revert what happened. What have I done wrong, and how can I import the circle function from script.py to test.py? Thank you in advance.

2 Answers

In order to import the circle function from script.py tp test.py you could make the following changes in your code:

In script.py:

import turtle


def circle(x, y, r, colour):
    turtle.showturtle()
    turtle.shape('classic')
    turtle.penup()
    turtle.setx(x)
    turtle.sety(y)
    turtle.pendown()
    turtle.pencolor(colour)
    turtle.fillcolor(colour)
    turtle.begin_fill()
    turtle.circle(r)
    turtle.end_fill()
    turtle.hideturtle()
    turtle.mainloop()

In test.py:

import script as file2

file2.circle(100, 100, 100, 'red')

By doing this your code runs only when the function is called.

I would go with an arrangement like:

script.py

import turtle

def circle(x, y, radius, colour):
    turtle.showturtle()
    turtle.penup()
    turtle.setposition(x, y)
    turtle.pendown()
    turtle.color(colour)
    turtle.begin_fill()
    turtle.circle(radius)
    turtle.end_fill()
    turtle.hideturtle()

test.py

import turtle
import script as file2

turtle.hideturtle()
turtle.shape('classic')

file2.circle(100, 100, 100, 'red')
file2.circle(50, 50, 50, 'blue')

turtle.mainloop()

This should allow you to call the circle function in script.py multiple times.

enter image description here

Related