简体   繁体   中英

How to speed up the turtle while in a tkinter canvas

I'm trying to make the turtle move faster, which I would normally do using

import turtle as t

t.speed(0)
t.tracer(0,0)

But when I have it in a canvas using RawTurtle(), I'm not sure how to do this.

root = tk.Tk() #create root window

#create turtle canvas
canvas = tk.Canvas(root,width=500,height=500)
canvas.pack()
t = turtle.RawTurtle(canvas)
t.ht()

Here's my code. Anyone know how?

First, either do one or the other of these, not both:

t.speed(0)
t.tracer(0,0)

The speed(0) aka speed('fastest') gets you the fastest drawing animation. The tracer(0) eliminates drawing animation altogether. They don't add together.

You can get maximum speed, ie eliminate drawing animation, in turtle embedded in a Canvas by using turtle's TurtleScreen() wrapper:

import tkinter as tk
from turtle import TurtleScreen, RawTurtle

root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()

screen = TurtleScreen(canvas)
screen.tracer(False)

turtle = RawTurtle(screen)

turtle.circle(100)

screen.tracer(True)
screen.mainloop()

I made a few edits to your code. For starters, you need to work all the commands after the t = turtle.RawTurtle(canvas) line. Then you need to add a .mainloop() function at the end.

This would be your final code:

import tkinter as tk
root = tk.Tk() #create root window
import turtle
#create turtle canvas
canvas = tk.Canvas(root,width=500,height=500)
canvas.pack()
t = turtle.RawTurtle(canvas)
t.speed(1)
t.forward(100)
t.ht()
root.mainloop()

When the speed is set to 1, this is the output: 输出

When the speed is set to 0, this is the output: 输出 2

Sorry about the gifs, and hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM