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.
Related
I dont know how to change the size of a turtle hitbox in python turtle graphics
I haven't tried anything yet because I'm new, and know very little about this. I've tried googling it, though, but nothing popped up.
from turtle import *
import turtle
from random import randint
import time
screen = turtle.Screen()
screen.setup(1920, 1080)
player = turtle.Turtle()
I want to add a button that you have to click to start right here
The game starts right here :
wn = turtle.Screen()
last_pressed = 'up'
def setup(col, x, y, w, s, shape):
player.penup()
player.up()
player.goto(x,y)
player.width(w)
player.turtlesize(s)
player.color(col)
player.lt(90)
player.down()
wn.onkey(up, "s")
wn.onkey(left, "d")
wn.onkey(right, "a")
wn.onkey(back, "w")
wn.onkey(quitTurtles, "Escape")
wn.listen()
wn.mainloop()
This may not be exactly what you are looking for, but this might work in your situation.
Detecting collision in Python turtle game
This is a thread on collision detection between objects and with some tweaking of numbers you could increase the hitbox of the turtle using the abs() function
I dont know how to change the size of a turtle hitbox in python turtle graphics
What do you mean by "hitbox"? I'm not sure what you mean by that (and neither does Google, apparently).
Do you mean that you want a rectangular button to click on? If that's the case, you could use the tkinter module together with the turtle module to create a button to click. (But be aware that it's not always easy to get the tkinter and turtle modules to work together to do what you want.)
If you want a button to click on, but don't need a Tkinter button, you could just try creating a new turtle in the shape of a rectangle that intercepts mouse clicks with onclick(). You can see an example of this if you run:
python3 -m turtledemo
and select Examples >> colormixer from the main menubar.
Or, if by "hitbox" you mean how to detect when one turtle has intercepted another turtle (as in, one has come close enough to the other to be considered a "hit"), I suggest querying each turtle's location, then using the Pythagorean Theorem to calculate the distance from each other. If this distance is within a predetermined threshold, consider the hitbox as being "hit."
You can see an example of this by typing:
python3 -m turtle
(Pay attention to the yellow turtle as he tries to catch up to the other turtle.)
I apologize if this answer isn't quite what you're looking for, but I'm just not sure what you mean by "hitbox." Maybe you could clarify?
I just saw this question today (2 years too late i know), and was having a similar problem / question.
What I ended up doing was running 3 distance checks (as i had increased my object size by 3) which differed along the x-axis (width). So it would check the distance between the ball(turtle) and the paddle (any 3 points and if it was shorter than X it would trigger the collision mechanic.
so it was something like :
check the ball class' ball object, and see how far away it is from the paddle,
and if its either in the center, or 30 pixels to the left or right of the center then hit.
if
ball.ball.distance(pad.paddle(), pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() - 30, pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() + 30, pad.paddle.ycor()) < 30
I have some code as follows:
# My code here
turtle.bye()
After that, is there any way I can reopen the turtle window.
I know you can do turtle.clearscreen() but that does not close the turtle window.
I will accept any answer which allows me to close the turtle graphics window and then reopen it without opening and running another python program to do this.
Thank you in advance
I've seen situations where the approach of #LukeTimmons worked but not always reliably and not in every situation. Give this solution a try:
import time
import turtle
turtle.dot(200, 'green')
time.sleep(2)
turtle.bye()
# These two lines (indirectly) resurrect turtle environment after turtle.bye()
turtle.Turtle._screen = None # force recreation of singleton Screen object
turtle.TurtleScreen._RUNNING = True # only set upon TurtleScreen() definition
turtle.dot(200, 'red')
turtle.mainloop()
It resets two flags that keep turtle from starting up again. It may be safer to create your own turtle after restart rather than use the default turtle which may point back to the departed environment.
There may be other ways but this is the only way I know.
from turtle import *
def turtle1():
#Your code here
turtle1()
turtle.bye()
turtle1()
This should re-run your code without re-typing it.
I've been trying to make a paint program in Python Turtle and for some reason it won't work. I'm using the pen() tool and my code looks like this
from turtle import *
import random
pen()
bgcolor('black')
pencolor('white')
pen.ondrag(pen.goto)
listen()
mainloop()
I've look at this http://docs.python.org/2/library/turtle.html and it says to type turtle.ondrag(turtle.goto) but since I'm using the pen it should work as pen.ondrag but it doesn't, so can someone please clear this up.
Thanks Jellominer
I will simplify and clarify the code given by the questionner:
from turtle import *
ts = Screen(); tu = Turtle()
ts.listen()
ondrag(tu.goto)
mainloop()
This works. You have to click on the turtle and drag it.
First, pen() is not the function you want. Second, although Pen is a synonym for Turtle, pen is not a synonym for turtle. Here's how to go about using ondrag() if you'd like to use Pen instead of Turtle:
from turtle import Pen, Screen, mainloop
def ondrag_handler(x, y):
pen.ondrag(None) # disable handler inside handler
pen.setheading(pen.towards(x, y)) # turn toward cursor
pen.goto(x, y) # move toward cursor
pen.ondrag(ondrag_handler)
screen = Screen()
screen.bgcolor('black')
pen = Pen()
pen.color('white')
pen.shapesize(2) # make it larger so it's easier to drag
pen.ondrag(ondrag_handler)
screen.listen()
mainloop() # screen.mainloop() preferred but not in Python 2
The turtle.ondrag(turtle.goto) makes for a nice short example in the documentation but in reality isn't practical. You want to disable the event handler while handling the event otherwise the events stack up against you. And it's nice to turn the mouse towards your cursor as you drag it.
from turtle import *
ts = Screen()
ondrag(goto)
shapesize(10)
pensize(40)
speed(0)
mainloop()
I think this will surely work.
You can change the size and other things
In here you are using the default turtle .
Sorry but you'll need to take care of the indentation
I'm trying to get the mouse position through Python turtle. Everything works except that I cannot get the turtle to jump to the position of the mouse click.
import turtle
def startmap(): #the next methods pertain to drawing the map
screen.bgcolor("#101010")
screen.title("Welcome, Commadore.")
screen.setup(1000,600,1,-1)
screen.setworldcoordinates(0,600,1000,0)
drawcontinents() #draws a bunch of stuff, works as it should but not really important to the question
turtle.pu()
turtle.onclick(turtle.goto)
print(turtle.xcor(),turtle.ycor())
screen.listen()
As I understand, the line that says 'turtle.onclick(turtle.goto)' should send the turtle to wherever I click the mouse, but it does not. The print line is a test, but it only ever returns the position that I sent the turtle last, nominally (0, 650) although this does not have major significance.
I tried looking up tutorials and in the pydoc, but so far I have not been able to write this successfully.
I appreciate your help. Thank you.
Edit: I need the turtle to go to the click position(done) but I also need it to print the coordinates.
You are looking for onscreenclick(). It is a method of TurtleScreen. The onclick() method of a Turtle refers to mouse clicks on the turtle itself. Confusingly, the onclick() method of TurtleScreen is the same thing as its onscreenclick() method.
24.5.4.3. Using screen events¶
turtle.onclick(fun, btn=1, add=None)
turtle.onscreenclick(fun, btn=1, add=None)¶
Parameters:
fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas
num – number of the mouse-button, defaults to 1 (left mouse button)
add – True or False – if True, a new binding will be added, otherwise it will replace a former binding
Bind fun to mouse-click events on this screen. If fun is None, existing bindings are removed.
Example for a TurtleScreen instance named screen and a Turtle instance named turtle:
>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>> # make the turtle move to the clicked point.
>>> screen.onclick(None) # remove event binding again
Note: This TurtleScreen method is available as a global function only under the name onscreenclick. The global function onclick is another one derived from the Turtle method onclick.
Cutting to the quick...
So, just invoke the method of screen and not turtle. It is as simple as changing it to:
screen.onscreenclick(turtle.goto)
If you had typed turtle.onclick(lambda x, y: fd(100)) (or something like that) you would probably have seen the turtle move forward when you clicked on it. With goto as the fun argument, you would see the turtle go to... its own location.
Printing every time you move
If you want to print every time you move, you should define your own function which will do that as well as tell the turtle to go somewhere. I think this will work because turtle is a singleton.
def gotoandprint(x, y):
gotoresult = turtle.goto(x, y)
print(turtle.xcor(), turtle.ycor())
return gotoresult
screen.onscreenclick(gotoandprint)
If turtle.goto() returns None (I wouldn't know), then you can actually do this:
screen.onscreenclick(lambda x, y: turtle.goto(x, y) or print(turtle.xcor(), turtle.ycor())
Let me know if this works. I don't have tk on my computer so I can't test this.
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.