In korean python textbook for highschool
to use turtle lib with the fastest pace user can use two verson of command.
import turtle as t
t.speed(0)
t.speed=0
is there a difference with two command?
I try to ask my teacher because of performance evaluation but.. unfortunately she didnt knowㅜㅠ..
t.speed = 0 overwrites the module function (or Turtle() method if you'd made an instance) with an integer 0:
>>> import turtle
>>> turtle.speed = 0
>>> turtle.speed("fastest")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
In general, all turtle API setters are function/method calls, not assignments. For example, turtle.setheading(90) and turtle.pencolor("red") set the heading to 90 degrees and the pen color to red, respectively.
If you want the turtle speed to be instantaneous, try turtle.tracer(0) and run turtle.update() to trigger a rerender after you've done your drawing.
As an aside, please don't use import turtle as t (although that's better than from turtle import *). It's unclear that t is the module and not a turtle instance, which makes ownership of the module confusing. Prefer making an instance of the turtle rather than calling global turtle functions, for example, t = turtle.Turtle().
t.speed=0 doesn't actually work (as ggorlen pointed out). If you want your trutle drawing to go really fast, you can make them happend off screen and only show the result at the end using screen(), tracer() and update():
Try this without the extra lines, then again after uncommenting the 3 lines:
import turtle as tg
def spiral(N):
tg.clear()
d = 1
for i in range(N):
tg.forward(d)
tg.left(20)
d+=0.3
## wn = tg.Screen() # Remove the 3 comments to make it fast
## wn.tracer(0)
tg.speed(0)
spiral(1000)
## wn.update()
Related
I wanted to make a blinking "Press SPACE to start!" screen and if SPACE was pressed, the program should shut down but I always get the turtle.terminator error. Can someone help me please?
from turtle import *
import pygame
while True:
x = 0
penup()
tracer(0)
if x == 0:
color("black")
goto(-80,-170)
write("Press SPACE to start!",font=50)
update()
pygame.time.delay(1*800)
x = 1
if x == 1:
color("white")
goto(-90,-180)
begin_fill()
goto(90,-180)
goto(90,-140)
goto(-90,-140)
goto(-90,-180)
end_fill()
update()
x = 0
pygame.time.delay(1*800)
def close():
bye()
onkey(close(),"Space")
done()
After integrating advice from the comments, it still raises an error when I use onkey(close,...) instead of onkey(close(),..).
It is "space", not "Space". Also, it is still correct to use onkey(close, ...).
The complete function would be onkey(close, "space")
There are a few issues here. A word of advice: work in small bursts and run your code often to validate all of your assumptions at each step of the way. This code looks as if it was all written in one fell swoop, and once it didn't work, there was too much complexity to isolate the bugs. Had you run the code to test it often as you went along, you'd see those errors immediately and the solutions would be more obvious.
Try to minimize the problem space by breaking your functionality into small pieces and validating each one.
First, let me provide my solution:
import turtle
def render_white_screen():
win.ontimer(render_press_space, delay_ms)
t.clear()
turtle.update()
def render_press_space():
win.ontimer(render_white_screen, delay_ms)
t.write(
"Press SPACE to start!",
move=False,
align="center",
font=("Arial", 20, "normal"),
)
turtle.update()
delay_ms = 800
turtle.tracer(0)
win = turtle.Screen()
win.onkey(turtle.bye, "space")
win.listen()
t = turtle.Turtle()
t.hideturtle()
t.color("black")
render_press_space()
turtle.mainloop()
Turtle is surprisingly not especially beginner-friendly and has a huge list of gotchas, so it's important to check the docs and do research on Stack Overflow as soon as you encounter an error.
Errors:
turtle.onkey(some_func(), "some key") is incorrect (assuming some_func isn't a higher-order function) because you're calling some_func rather than passing it as the handler. This should be turtle.onkey(some_func, "some key"). This happens to trigger the terminator error because terminator occurs when you run turtle code after exiting, which is what your handler does. See Python Turtle.Terminator even after using exitonclick() and onkeypress( ) function in turtle module problem.
turtle.onkey(space_handler, "Space") should be turtle.onkey(space_handler, "space") (lowercase). See Couldn't get rid of (_tkinter.TclError: bad event type or keysym "UP") problem.
You must call turtle.listen() to activate key handlers that you've registered. See Turtle.onkeypress not working (Python).
Suggestions/better practices:
Always use import turtle, never from turtle import *. The reason is that from turtle import * dumps 160+ functions into the global namespace, causing potential clashes with your own functions. Many of these functions have common names like update and reset that can easily cause confusion and bugs. Turtle has a module-level instance ostensibly to avoid confusion for beginners, but it only winds up introducing more problems in the long run than simply creating a turtle instance.
Don't import pygame just to sleep. Python has a native function sleep available in the time module. But even better is to use turtle's ontimer callback as shown above.
You can clear the screen with t.clear().
It's my first time here and I'm new in the Python.
When I wrote this code
import turtle
ws = turtle.Screen()
aTurtle = turtle.Turtle()
colors = [ "pink","yellow","blue","green","white","red"]
sketch = turtle.pen()
turtle.bgcolor("black")
for i in range(200):
sketch.pencolor(colors[i % 6])
sketch.width(i/100+1)
sketch.forward(i)
sketch.left(59)
turtle.done()
Then I get this error with black screen
Traceback (most recent call last):
File "C:/Users/wi n7/AppData/Local/Programs/Python/Python37/Lib/draw1.py", line 10, in <module>
sketch.pencolor(colors[i % 6])
AttributeError: 'dict' object has no attribute 'pencolor'
First of all, thanks for posting a minimal, complete example and the full error message with stack trace. That's half the battle--collecting all of the information you need to perform debugging (or provide that info to others to debug for you). The next step is to use this information to actually debug the program. I'll walk you through how I do it in detail so you can do it on your own next time on any problem you might encounter.
The error tells us that sketch.pencolor fails because the sketch is a dictionary object which has no .pencolor attribute. Since .pencolor is a Turtle method, you probably think sketch is a Turtle object. But printing the type just above the error line with print(type(sketch)) or looking at the error message tells us that, indeed, sketch is a dictionary (dict). Running print(dir(sketch)) further confirms that pencolor is not an attribute or method available on dict.
So trace the code backwards from the point of failure. How did sketch become a dict unexpectedly? Find the last (and only) assignment: sketch = turtle.pen().
Looking at the docs for the Turtle.pen() method reveals what it returns:
Return or set the pen’s attributes in a "pen-dictionary"
The turtle library has a somewhat odd design where methods without parameters are getters that return a value, while methods that have a parameter are setters that set properties on the turtle. You're using .pen() in getter mode since there are no parameters. So sketch is a pen-dictionary because that's the return value of .pen().
It's a bit semantically confusing, because you might think you need to get a pen to draw with turtle. Think of the pen as a thing the turtle holds, but you don't touch directly, so you won't need to get the pen for just about any reason other than to see what its current properties are, or to save it to permanent storage or something like that. You'll likely only set pen properties.
Another red flag: unused variables. You took the time to create aTurtle but never did anything with it. Actually, this is the correct variable to be using instead of sketch (although in Python, the correct naming convention is snake_case, a_turtle).
All you need to do is remove sketch = turtle.pen() and use aTurtle everywhere sketch was. That's the real turtle you want to draw with.
In case there's any issue doing this (try it yourself), here's the code:
import turtle
a_turtle = turtle.Turtle()
colors = ["pink", "yellow", "blue", "green", "white", "red"]
turtle.bgcolor("black")
for i in range(200):
a_turtle.pencolor(colors[i % 6])
a_turtle.width(i / 100 + 1)
a_turtle.forward(i)
a_turtle.left(59)
turtle.done()
I am learning turtle graphics in python and for some reason there is a second turtle on the screen and I haven't even created a second turtle. How can I get rid of the second turtle?
import turtle
s = turtle.getscreen()
t = turtle.Turtle()
for i in range(4):
t.fd(100)
t.rt(90)
turtle.exitonclick()
The second turtle at the starting location appears because of the line s = turtle.getscreen().
This line is not needed (you do not use s), and if you remove it this turtle disappears but the rest of the code seems to work as before.
The turtle library exposes two interfaces, a functional one (for beginners) and an object-oriented one. You got that extra turtle because you mixed the two interfaces (and #mkrieger1's solution doesn't fix that completely).
I always recommend an import like:
from turtle import Screen, Turtle
screen = Screen()
turtle = Turtle()
for _ in range(4):
turtle.forward(100)
turtle.right(90)
screen.exitonclick()
This gives you access to the object-oriented interface and blocks the functional one. Mixing the two leads to all sorts of bugs and artifacts.
To combine the answer from mkrieger1 and cdlane, you could replace
s = turtle.getscreen()
with
s = turtle.Screen()
You've still got a variable holding the screen (in case you should ever need it), and it doesn't generate that extra turtle in the center.
I'm new to the Python turtle library and I have a problem that confuses me a lot.
I can work with turtle in real time, but when I write a program and I save it to a file, I can't run it.
The code I have written follows below:
from turtle import *
turtle.Pen(9999999)
penup()
for i in range(16):
write(i,align='center')
forward(25)
goto(0,-5)
x=0
right(90)
for i in range(16):
pendown()
forward(400)
penup()
x+=25
goto(x,-5)
but it didn't work at all.
It gave me this error:
Traceback (most recent call last):
File "C:\Users\Nobody\Desktop\main.py", line 3, in <module>
turtle.Pen(9999999)
NameError: name 'turtle' is not defined
I think it doesn't import turtle at all.
You named your own file turtle.py
So your main.py is importing your own turtle.py, not python's turtle module.
Delete turtle.py from your desktop (and the turtle.pyc that was automatically generated).
from turtle import *
this line imports everything to the default module namespace, so you don't have to add turtle. prefix to anything
Instead of turtle.Pen you want just Pen
from turtle import *
Means literally: import all from the file turtle.py.
Python interpreter firstly checks in the current directory for any match with turtle.py and if not found anything, it will search inside library folders.
In your case, you are importing all classes, all functions and all global variables (at least not private ones) from turtle.py so you need to use
Pen(9999999)
Instead of
turtle.Pen(9999999)
Here's a rework of your code that runs fine for me:
from turtle import *
speed('fastest')
penup()
for i in range(16):
write(i, align='center')
forward(25)
goto(0, -5)
right(90)
x = 0
for i in range(16):
pendown()
forward(400)
penup()
x += 25
goto(x, -5)
hideturtle()
done()
If it runs for you, great. If it doesn't, let us know the complete error you're getting as a comment follow on to this answer. Make sure you don't have a personal turtle.py file, as #nosklo notes.
My advice is when it comes to invoking library functions, it's better to lookup rather than make up.
I want to have multiple turtles for a game. turtle is the main character and monster is another turtle i've added. How to I add a shape to it. Heres the code:
import turtle
monster = turtle.Turtle()
monster.addshape('enemt.gif')
monster.shape('enemt.gif')
monster.goto(0, 0)
I get the error
Traceback (most recent call last):
File "C:\Users\Alfie\Desktop\Tutorial Game\Tutorial Game.py", line 77, in <module>
monster.addshape('enemt.gif')
AttributeError: 'Turtle' object has no attribute 'addshape'
Rereading the documentation, addshape() is listed as a method of turtle but the examples show it as a method of the screen, which works:
import turtle
screen = turtle.Screen()
screen.addshape('enemt.gif')
monster = turtle.Turtle('enemt.gif')
monster.goto(0, 0)
turtle.done()
Actually, turtle.addshape('enemt.gif') also works in this code.
All methods of the Turtle class are also available as top level functions that operate on the default (unnamed) turtle instance. All methods of the Screen class are also available as top level functions that operate on the default (sole) screen instance.
I found it, but I'll answer for anyone else with the problem :P
monster = turtle.Turtle()
monster.addshape('enemt.gif')
monster.goto(0, 0)
monster.shape('enemt.gif')
monster.addshape('enemt.gif') doesn't work because addshape is only for turtle, not multiple. Now if you use
turtle.addshape()
it works! But you use monster.shape() sorry if I can't answer these questions, if anyone knows the actual reason that this works, edit this please :P