How to add an image to a turtle object in python? - python

# register shape
turt = turtle.Turtle()
turt.register_shape('player.png')
# player
p = turtle.Turtle()
p.speed(0)
p.color('magenta')
p.shape('player.png')
p.shapesize(2)
p.setheading(0)
p.penup()
p.setposition(-700, 0)
hp = 3
then i get this error: 'Turtle' object has no attribute 'register_shape'

register_shape is not a method on Turtle objects, it's a global function.
So, instead of this:
turt.register_shape('player.png')
… do this:
turtle.register_shape('player.png')
Also, notice that you don't have any use for that turt turtle. Your app only wants to display a single turtle, p, so don't create any others.
Finally, even after you fix this:
At least according to the docs, only GIF images are supported, but you're trying to use a PNG image. The docs may be wrong about that, but there's a good chance they're right, and this is going to fail.
If so, the only way to fix it is to use some other program (it could be one you write yourself in 4 lines of Pillow code, or it could be something like MSPaint or Preview, or a command-line tool like ImageMagick convert) to make a GIF image out of your PNG image.

Related

Changing turtle cursor shape using Python

Is there a simple way to change the turtle cursor to an open hand and back to normal cursor?
I have searched and did not find a thing.
I'm using Python turtle on Windows.
Any answer is appreciated!
There are few preset shapes for turtle such as, arrow, circle, etc. You can find them here https://docs.python.org/3.3/library/turtle.html?highlight=turtle#turtle.shape, or you could use the turtle.register_shape(image_name) function. Hope this helps!
Is there a simple way to change the cursor to an open hand and back to
normal cursor?
Yes, you first want the register_shape() method of the screen, passing it your GIF file name. Then you pass the same file name to the shape() method of turtle. (Newer implementations of turtle and tkinter accept more file types but traditionally this needs to be a GIF.)
Demonstrating with a guinea pig GIF found on iconsplace.com, the following code switches from the turtle cursor that comes with the Python library to a guinea pig cursor from that site when you click on the window:
from turtle import Screen, Turtle
IMAGE = "guinea-pig-icon-24.gif"
def change(x, y):
turtle.shape(IMAGE)
screen = Screen()
screen.register_shape(IMAGE)
turtle = Turtle('turtle')
screen.onclick(change)
screen.mainloop()
Switching back again is simple as calling the shape() method again.

Turtle Library in Python

I am having a huge issue using the turtle library. I have to write my initials AR for an assignment. Can anyone help?
import turtle
turtlescreen
turtle.pos(400,400)
turtle.forward()
Here is the code I am trying to use. I am trying to right my initial "AR" with it.
You've managed to cram three errors into four lines of code. First, you don't need this and it's an error:
turtlescreen
so toss it. Second, the pos() function returns the current turtle postion, not set it. So instead of:
turtle.pos(400,400)
You want:
turtle.setpos(400, 400)
and finally, as #Jamie notes, you need to pass a distance (in pixels) to forward(). So instead of:
turtle.forward()
Something like he suggests:
turtle.forward(15)
Complete code:
import turtle
turtle.setpos(400, 400)
turtle.forward(15)
turtle.done()
Your turtle.forward() requires an input variable in pixels. See the documentation for turtle.forward:
Move the turtle forward by the specified distance, in the direction the turtle is headed.
Try changing:
turtle.forward()
to something like:
turtle.forward(15)
There's a few mistakes I can see. Firstly, there is no command called turtlescreen so you can remove that. Next, instead of tom.pos try using tom.setpos(x, y) or tom.goto (x, y). Lastly, you should put a value in tom.forward (length). I also recommend going through the Python Turtle documentation, https://docs.python.org/3.3/library/turtle.html?highlight=turtle

Cant Add Shape (image)

I am trying to add a image to my code but it keep raising the error
Bad arguments for register_shape
I am following the tutorial at http://blog.trinket.io/using-images-in-turtle-programs/
my code is:
import turtle
screen = turtle.Screen()
# click the image icon in the top right of the code window to see
# which images are available in this trinket
image = "C:\...\rocketship.png"
# add the shape first then set the turtle shape
screen.addshape(image)
turtle.shape(image)
I am using python 2.6.
furthermore when I use the function of
screen.bgpic("C:...\Backgrounds\giphy2.gif")
The background works.
You may look for answers here:
How can i add an image (Python)
The turtle module does have support for images, but only GIF images, not PNG or any other format. As the docs for addshape say:
name is the name of a gif-file and shape is None: Install the corresponding image shape.

Is it possible to parent to only one or two axes in Blender?

I'm in the process of creating a 2d platformer using the Blender Game Engine. I'm having trouble getting the camera to follow my character and keep him in the center of the screen. Initially, I tried simply parenting the camera to my character, but whenever my character turns (rotates around the Z-axis 180 degrees), so does my camera, making it face the back of the level. So, I was wondering if there was a way to "parent" only one or two axes of an object to another, or restrain an axes from moving even if it is parented. This way I could keep the camera from rotating, but still have it follow on the Y and Z axes.
One thing I looked into was using Python code. I came up with...
import bpy
char = bpy.data.objects['HitBox']
obj = bpy.data.objects['Camera']
obj.location.x = 69.38762 # this is the set distance from the character to camera
obj.location.y = char.location.y
obj.location.z = char.location.z
bpy.data.scenes[0].update()
I realize I need a loop for this after assigning the 'char' variable, but I can't get any Python loops working that would run through the entire game, as 'while' loops crash the BGE. If you could help with either the parenting issue, or the Python code, I'd really appreciate it.
you just need to use the bge module, because it is for the game engine. So your problem is: you used blender python, but not bge python. Try to reach the camera with cam = bge.logic.getCurrentScene().active_camera. ... so this should work:
import bge
def main():
cam = bge.logic.getCurrentScene().active_camera
obj = bge.logic.getCurrentController().owner
obj.worldPosition.y = cam.worldPosition.y
obj.worldPosition.z = cam.worldPosition.z
main()
(Attach this script to your 'HitBox' with a true triggered always sensor so it can cycle forever.)
Other solution:
You can try to make vertex parent to your player.

When saving turtle graphics to an .eps file, the background color shows on the screen but is not saved in the .eps file

I am new to Python and have been working with the turtle module as a way of learning the language.
Thanks to stackoverflow, I researched and learned how to copy the image into an encapsulated postscript file and it works great. There is one problem, however. The turtle module allows background color which shows on the screen but does not show in the .eps file. All other colors, i.e. pen color and turtle color, make it through but not the background color.
As a matter of interest, I do not believe the import of Tkinter is necessary since I do not believe I am using any of the Tkinter module here. I included it as a part of trying to diagnose the problem. I had also used bgcolor=Orange rather than the s.bgcolor="orange".
No Joy.
I am including a simple code example:
# Python 2.7.3 on a Mac
import turtle
from Tkinter import *
s=turtle.Screen()
s.bgcolor("orange")
bob = turtle.Turtle()
bob.circle(250)
ts=bob.getscreen()
ts.getcanvas().postscript(file = "turtle.eps")
I tried to post the images of the screen and the .eps file but stackoverflow will not allow me to do so as a new user. Some sort of spam prevention. Simple enough to visualize though, screen has background color of orange and the eps file is white.
I would appreciate any ideas.
Postscript was designed for making marks on some medium like paper or film, not raster graphics. As such it doesn't have a background color per se that can be set to given color because that would normally be the color of the paper or unexposed film being used.
In order to simulate this you need to draw a rectangle the size of the canvas and fill it with the color you want as the background. I didn't see anything in the turtle module to query the canvas object returned by getcanvas() and the only alternative I can think of is to read the turtle.cfg file if there is one, or just hardcode the default 300x400 size. You might be able to look at the source and figure out where the dimensions of the current canvas are stored and access them directly.
Update:
I was just playing around in the Python console with the turtle module and discovered that what the canvas getcanvas() returns has a private attribute called _canvas which is a <Tkinter.Canvas instance>. This object has winfo_width() and winfo_height() methods which seem to contain the dimensions of the current turtle graphics window. So I would try drawing a filled rectangle of that size and see if that gives you what you want.
Update 2:
Here's code showing how to do what I suggested. Note: The background must be drawn before any other graphics are because otherwise the solid filled background rectangle created will cover up everything else on the screen.
Also, the added draw_background() function makes an effort to save and later restore the graphics state to what it was. This may not be necessary depending on your exact usage case.
import turtle
def draw_background(a_turtle):
""" Draw a background rectangle. """
ts = a_turtle.getscreen()
canvas = ts.getcanvas()
height = ts.getcanvas()._canvas.winfo_height()
width = ts.getcanvas()._canvas.winfo_width()
turtleheading = a_turtle.heading()
turtlespeed = a_turtle.speed()
penposn = a_turtle.position()
penstate = a_turtle.pen()
a_turtle.penup()
a_turtle.speed(0) # fastest
a_turtle.goto(-width/2-2, -height/2+3)
a_turtle.fillcolor(turtle.Screen().bgcolor())
a_turtle.begin_fill()
a_turtle.setheading(0)
a_turtle.forward(width)
a_turtle.setheading(90)
a_turtle.forward(height)
a_turtle.setheading(180)
a_turtle.forward(width)
a_turtle.setheading(270)
a_turtle.forward(height)
a_turtle.end_fill()
a_turtle.penup()
a_turtle.setposition(*penposn)
a_turtle.pen(penstate)
a_turtle.setheading(turtleheading)
a_turtle.speed(turtlespeed)
s = turtle.Screen()
s.bgcolor("orange")
bob = turtle.Turtle()
draw_background(bob)
ts = bob.getscreen()
canvas = ts.getcanvas()
bob.circle(250)
canvas.postscript(file="turtle.eps")
s.exitonclick() # optional
And here's the actual output produced (rendered onscreen via Photoshop):
I haven't found a way to get the canvas background colour on the generated (Encapsulated) PostScript file (I suspect it isn't possible). You can however fill your circle with a colour, and then use Canvas.postscript(colormode='color') as suggested by #mgilson:
import turtle
bob = turtle.Turtle()
bob.fillcolor('orange')
bob.begin_fill()
bob.circle(250)
bob.begin_fill()
ts = bob.getscreen()
ts.getcanvas().postscript(file='turtle.eps', colormode='color')
Improving #martineau's code after a decade
import turtle as t
Screen=t.Screen()
Canvas=Screen.getcanvas()
Width, Height = Canvas.winfo_width(), Canvas.winfo_height()
HalfWidth, HalfHeight = Width//2, Height//2
Background = t.Turtle()
Background.ht()
Background.speed(0)
def BackgroundColour(Colour:str="white"):
Background.clear() # Prevents accumulation of layers
Background.penup()
Background.goto(-HalfWidth,-HalfHeight)
Background.color(Colour)
Background.begin_fill()
Background.goto(HalfWidth,-HalfHeight)
Background.goto(HalfWidth,HalfHeight)
Background.goto(-HalfWidth,HalfHeight)
Background.goto(-HalfWidth,-HalfHeight)
Background.end_fill()
Background.penup()
Background.home()
BackgroundColour("orange")
Bob=t.Turtle()
Bob.circle(250)
Canvas.postscript(file="turtle.eps")
This depends on what a person is trying to accomplish but generally, having the option to select which turtle to use to draw your background to me is unnecessary and can overcomplicate things so what one can do instead is have one specific turtle (which I named Background) to just update the background when desired.
Plus, rather than directing the turtle object via magnitude and direction with setheading() and forward(), its cleaner (and maybe faster) to simply give the direct coordinates of where the turtle should go.
Also for any newcomers: Keeping all of the constants like Canvas, Width, and Height outside the BackgroundColour() function speeds up your code since your computer doesn't have to recalculate or refetch any values every time the function is called.

Categories