Creating Turtle objects in a class with python - python

I am trying to create turtle objects with a class for my project which is a game. Each "Plane" object consists of:
plane3 = RawTurtle(screen)
plane3.ht()
plane3.color("red")
plane3.shape("plane.gif")
plane3.penup()
plane3.speed('fastest')
plane3.setposition(-270, 200)
plane3.setheading(360)
When putting this into a class and looking at other stack overflows questions to find out what to do, i threw together the following code:
class planes():
def __init__(self):
self.RawTurtle = RawTurtle(screen)
#self.hideturtle()
self.color = "red"
self.shape = ("plane.gif")
#self.penup()
self.speed = "fastest"
self.setposition = (-270, 100)
self.setheading = 360
Plane4 = planes()
When the code is run the turtle takes no shape or colour and is just a black triangle even though it causes no errors. However, errors do occur with the plane.hideturtle and plane.penup() functions which is why they are commented out.
File "C:/Users/marco/Desktop/Trooper shooter/TrooperShooter.py", line 694, in init
self.hideturtle()
AttributeError: 'planes' object has no attribute 'hideturtle'
Planes outside the class work perfectly and all planes are exactly identical. Any help is appreciated!

hideturtle() and penup() are both methods for the RawTurtle class, you haven't defined them for your planes class. So instead of this:
self.hideturtle()
self.penup()
you should have this:
self.RawTurtle.hideturtle()
self.RawTurtle.penup()

I believe your real problem is that your designed your plane class such that it has a turtle instead of designing it such that it is a turtle.
Taking the has a approach, every time you want to enable some additional turtle feature on your plane, you have to add a method to pass the call through to the contained turtle. Taking the is a approach, all turtle methods are in play:
from turtle import RawTurtle, TurtleScreen
from tkinter import Tk, Canvas, RIGHT
class Plane(RawTurtle):
def __init__(self):
super().__init__(screen)
self.hideturtle()
self.color('red')
self.shape('plane.gif')
# self.speed('fastest') # commented out while debugging
self.penup()
self.setposition(-270, 100)
self.setheading(0)
self.showturtle()
root = Tk()
canvas = Canvas(root, width=600, height=400)
canvas.pack(side=RIGHT)
screen = TurtleScreen(canvas)
screen.register_shape('plane.gif')
plane4 = Plane()
plane4.forward(400)
screen.mainloop()

Related

How to set turtle tracer false using tkinter?

I have to generate two turtle windows and draw in each one, so I'm using tkinter to create and show the windows. My code currently opens the right screen and draws in it, but the turtle is really slow so I want to set the turtle tracer to false to use the update function, but I can't figure out how to.
This is my turtle_interpreter.py file, which has all the functions I use to draw the L-system:
import turtle
from tkinter import *
class Window(Tk):
def __init__(self, title, geometry):
super().__init__()
self.running = True
self.geometry(geometry)
self.title(title)
self.protocol("WM_DELETE_WINDOW", self.destroy_window)
self.canvas = Canvas(self)
self.canvas.pack(side=LEFT, expand=True, fill=BOTH)
self.turtle = turtle.RawTurtle(turtle.TurtleScreen(self.canvas))
def update_window(self):
'''
sets window to update
'''
if self.running:
self.update()
def destroy_window(self):
'''
sets window to close
'''
self.running = False
self.destroy()
def drawString(turt, dstring, distance, angle):
'''Interpret the characters in string dstring as a series
of turtle commands. Distance specifies the distance
to travel for each forward command. Angle specifies the
angle (in degrees) for each right or left command. The list
of turtle supported turtle commands is:
F : forward
- : turn right
+ : turn left
'''
for char in dstring:
if char == 'F':
turt.forward(distance)
elif char == '-':
turt.right(angle)
elif char == '+':
turt.left(angle)
def place(turt, xpos, ypos, angle=None):
'''
places turtle at given coordinates and angle
'''
turt.penup()
turt.goto(xpos, ypos)
if angle != None:
turt.setheading(angle)
turt.pendown()
def goto(turt, xpos, ypos):
'''
moves turtle to given coordinates
'''
turt.penup()
turt.goto(xpos, ypos)
turt.pendown()
def setColor(turt, color):
'''
sets turtle color
'''
turt.color(color)
And this is the file where the functions get called. Running it draws the L-system.
import turtle_interpreter as turt_int
import lsystem_scene_three as lsystem
def turtle_scene_two():
'''
generates scene two
'''
# create window
win_two = turt_int.Window('Turtle Scene 2', '640x480+650+0')
# assign turtle
turt2 = win_two.turtle
# lsystem setup
lsystemFile = lsystem.Lsystem('lsystem_scene_two.txt')
tstr = lsystemFile.buildString(4)
# draw stuff
turt_int.setColor(turt2, (0, 0, 0))
turt_int.place(turt2, 0, -200, 90)
turt_int.drawString(turt2, tstr, 4, 90)
# update window (loop)
while win_two.running:
win_two.update_window()
turtle_scene_two()
Hope this makes sense. Let me know if it doesn't.
Appreciate your help!
Tried a few things but nothing was promising. Calling turtle generates another screen (which I don't want).
Since you didn't provide all your code, I can't test this, so I'm guessing a good start would be changing this:
self.turtle = turtle.RawTurtle(turtle.TurtleScreen(self.canvas))
to something like:
screen = turtle.TurtleScreen(self.canvas)
screen.tracer(False)
self.turtle = turtle.RawTurtle(screen)

creating boxes using turtle

can someone please help me making few boxes, each on different axis co-ordinates using turtle,
P.S. trying to use class and objects in below code:
import turtle
from turtle import *
# window:
window = turtle.Screen()
window.bgcolor("white")
window.title("Process flow")
class a:
penup()
shape("square")
speed(0)
def __init__(self, reshape, color, location):
self.reshape = reshape
self.color = color
self.location = location
start_node1 = a(reshape=shapesize(stretch_wid=1, stretch_len=3), color=color("light blue"), location=goto(0, 300))
start_node2 = a(reshape=shapesize(stretch_wid=1, stretch_len=3), color=color("yellow"), location=goto(0, 270))
print(start_node1)
print(start_node2)
done()
You seem to have strung together random bits of code with the hope that it would work. E.g. argument calls like:
..., location=goto(0, 300)
pass None onto your initializer as that's what goto() returns. And importing turtle two different ways:
import turtle
from turtle import *
is a sign you're in conceptual trouble. Below is my rework of your code to display boxes of different colors and sizes at various locations that tries to retain as much of the "flavor" of your original code as possible:
from turtle import Screen, Turtle
class Box(Turtle):
def __init__(self, reshape, color, location):
super().__init__(shape='square', visible=False)
self.shapesize(**reshape)
self.color(color)
self.speed('fastest')
self.penup()
self.goto(location)
self.showturtle()
screen = Screen()
screen.title("Process flow")
start_node1 = Box(reshape={'stretch_wid':1, 'stretch_len':3}, color='light blue', location=(100, 300))
start_node2 = Box(reshape={'stretch_wid':2, 'stretch_len':4}, color='yellow', location=(-100, 270))
screen.exitonclick()

Python Turtle Objects in conjuction with tkinter is it possible?

I'm having an issue when I run my main.py, it shows two screens. I know it's because I'm calling an object, just not sure if it's possible to use objects and have it show up on the tkinter window.
main.py
import tkinter as tk
from turtle import TurtleScreen
from createDotTest import Dot
top = tk.Tk()
canvas = tk.Canvas(top, width=600, height=600)
canvas.pack()
screen = TurtleScreen(canvas)
screen.tracer(0)
list_of_points = []
list_of_lines = []
for x in range(100):
dot = Dot()
list_of_points.append(dot)
screen.mainloop()
createDotTest.py
from turtle import Turtle
import random
class Dot(Turtle):
def __init__(self):
super().__init__()
x_pos = random.randint(-280, 280)
y_pos = random.randint(-280, 280)
self.shapesize(.2,.2)
self.penup()
self.shape('circle')
self.goto(x_pos, y_pos)
self.stamp()
I tried also replacing Turtle as TurtleRaw in the createDotTest.py but I get
raise TurtleGraphicsError("bad canvas argument %s" % canvas)
turtle.TurtleGraphicsError: bad canvas argument None
This question looks similar to Combine tkinter and turtle
I am not sure but this may help you

Is there a way to make turtle-graphics object oriented?

class Paddle(turtle.Turtle):
def __init__(self, pos, color, shape, speed, shape_size):
self.turtle.pos = turtle.goto(pos)
self.turtle.color = turtle.color(color)
self.turtle.shape = turtle.shape(shape)
self.turtle.speed = turtle.speed(speed)
self.turtle.shapesize = turtle.shapesize(shapesize)
OOP Python turtle module
I have tried to make my game object oriented by trying this code block above, but I get the AttributeError: 'Paddle' object has no attribute 'turtle' traceback. Honestly I have never done OOP with inheritance and modules combined so I'm not quite sure what I'm supposed to do. If you have a resource where I can learn how inheritance works with modules, I'd greatly appreciate it!
Python turtle graphics is object-oriented. The question is, "Is there a way to make your program object-oriented?" We can implement the spirit of what your code is trying to do in an object-oriented fashion something like:
from turtle import Screen, Turtle
class Paddle(Turtle):
def __init__(self, position, color, shape, speed, stretch):
super().__init__(shape=shape, visible=False)
self.penup()
self.goto(position)
self.color(color)
self.shape(shape)
self.speed(speed)
self.shapesize(stretch, 1)
self.showturtle()
screen = Screen()
paddle1 = Paddle((100, 100), 'blue', 'square', 'fastest', 3)
paddle2 = Paddle((-100, 100), 'red', 'square', 'fastest', 3)
screen.exitonclick()
You were mixing the OOP concepts of isa and contains. The above solution only uses isa

Turtle in Tkinter creating multiple windows

I am attempting to create a quick turtle display using Tkinter, but some odd things are happening.
First two turtle windows are being created, (one blank, one with the turtles), secondly, any attempt of turning the tracer off is not working.
This might be a simple fix but at the moment I cannot find it.
Any help would be appreciated,
Below is the code:
import tkinter as tk
import turtle
window = tk.Tk()
window.title('Top 10\'s')
def loadingscreen():
canvas = tk.Canvas(master = window, width = 500, height = 500)
canvas.pack()
arc1 = turtle.RawTurtle(canvas)
arc2 = turtle.RawTurtle(canvas)
#clean up the turtles and release the window
def cleanup():
turtle.tracer(True)
arc1.ht()
arc2.ht()
turtle.done()
#animate the turtles
def moveTurtles(rangevar,radius,extent,decrease):
for distance in range(rangevar):
arc1.circle(-radius,extent = extent)
arc2.circle(-radius,extent = extent)
radius -= decrease
#Set the turtle
def setTurtle(turt,x,y,heading,pensize,color):
turt.pu()
turt.goto(x,y)
turt.pd()
turt.seth(heading)
turt.pensize(pensize)
turt.pencolor(color)
#draw on the canvas
def draw():
#set variables
rangevar = 200
radius = 200
decrease = 1
extent = 2
#setup and draw the outline
turtle.tracer(False)
setTurtle(arc1,0,200,0,40,'grey')
setTurtle(arc2,14,-165,180,40,'grey')
moveTurtles(rangevar,radius,extent,decrease)
#setup and animate the logo
turtle.tracer(True)
setTurtle(arc1,0,200,0,20,'black')
setTurtle(arc2,14,-165,180,20,'black')
moveTurtles(rangevar,radius,extent,decrease)
#main program
def main():
turtle.tracer(False)
arc1.speed(0)
arc2.speed(0)
draw()
cleanup()
if __name__ == "__main__":
try:
main()
except:
print("An error occurred!!")
loadingscreen()
Essentially I am creating a Tk window, then a canvas, then two turtles, and then animating these turtles
My guess is you're trying to call turtle screen methods without actually having a turtle screen. When turtle is embedded in tkinter like this, you can overlay a Canvas with a TurtleScreen instance which will provide some, but not all, of the screen features of the standalone turtle:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen
def cleanup():
""" hide the turtles """
arc1.hideturtle()
arc2.hideturtle()
def moveTurtles(rangevar, radius, extent, decrease):
""" animate the turtles """
for _ in range(rangevar):
arc1.circle(-radius, extent=extent)
arc2.circle(-radius, extent=extent)
radius -= decrease
def setTurtle(turtle, x, y, heading, pensize, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.setheading(heading)
turtle.pensize(pensize)
turtle.pencolor(color)
def draw():
# set variables
rangevar = 200
radius = 200
decrease = 1
extent = 2
screen.tracer(False) # turn off animation while drawing outline
# setup and draw the outline
setTurtle(arc1, 0, 200, 0, 40, 'grey')
setTurtle(arc2, 14, -165, 180, 40, 'grey')
moveTurtles(rangevar, radius, extent, decrease)
screen.tracer(True) # turn animation back on for the following
# setup and animate the logo
setTurtle(arc1, 0, 200, 0, 20, 'black')
setTurtle(arc2, 14, -165, 180, 20, 'black')
moveTurtles(rangevar, radius, extent, decrease)
# main program
window = tk.Tk()
window.title("Top 10's")
canvas = tk.Canvas(master=window, width=500, height=500)
canvas.pack()
screen = TurtleScreen(canvas)
arc1 = RawTurtle(screen)
arc1.speed('fastest')
arc2 = RawTurtle(screen)
arc2.speed('fastest')
draw()
cleanup()
Another suggestion: don't mess with tracer() until after everything else is working and then (re)read it's documentation carefully.
I just have the answer for the two windows that are being created: the one with the turtles is obvious, and the blank one is for the main root window that you define (window = tk.Tk()). If you want it not to appear at all, you can add the following line right after its definition:
window.withdraw()
I found this solution here and here.

Categories

Resources