Exiting the turtle screen


#1

Hi,

I am made this class to create points, determine the area of the figure, and draw the figure using the turtle module. I use Pycharm’s Python Console to run the class. I want to display the figure, exit, modify the list, display the figure, … but I get an error once I close the window by clicking the red x button and can’t display the new figure. How do I fix this? Also, is there any way to improve my code as a whole? I am not sure if I should place draw_figure() and calculate_area() in the class because they don’t have self as a parameter.

Thanks!

import turtle


class Coordinate:

    list_of_points = []
    number_of_points = 0

    def __init__(self, x, y):
        self.x = x
        self.y = y
        Coordinate.number_of_points += 1
        Coordinate.list_of_points.append([self.x, self.y])

    def remove(self):
        Coordinate.list_of_points.remove([self.x, self.y])

    def draw_figure():
        turtle.hideturtle()
        turtle.penup()
        turtle.goto(Coordinate.list_of_points[0])
        turtle.pendown()

        for point in Coordinate.list_of_points:
            turtle.goto(point)
            turtle.dot(3, "red")

        turtle.goto(Coordinate.list_of_points[0])
        turtle.exitonclick()

    def calculate_area():  # signed area
        if len(Coordinate.list_of_points) == 0:
            print("There are no points.")
            return
        elif len(Coordinate.list_of_points) == 1:
            print("There is only one point.")

        else:  # shoelace formula
            area = 0
            for index in range(len(Coordinate.list_of_points) - 1):
                area += Coordinate.list_of_points[index][0] * Coordinate.list_of_points[index + 1][1]\
                    - Coordinate.list_of_points[index + 1][0] * Coordinate.list_of_points[index][1]

            area += Coordinate.list_of_points[-1][0] * Coordinate.list_of_points[0][1]\
                - Coordinate.list_of_points[0][0] * Coordinate.list_of_points[- 1][1]

            area = 0.5 * abs(area)

            print("Area of the figure: ", area)


#2

maybe pycharm is using the main thread to watch your variables (perhaps it should be doing it the other way around)

the other error is probably from not cleanly resetting the state of turtle, perhaps there was some cleanup you were supposed to do before opening another window, you’d know better than me


#3

Can you explain what the main thread is? I’m new to programming. Thanks


#4

It’s the thread the program starts with. I’m guessing pycharm runs its own code and starts another thread for yours to run in.

I’d run the program without pycharm.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.