Skip to content Skip to sidebar Skip to footer

How Can I Close And Re-open Turtle Screen In Python

Could you please guide me? After I draw a square, how can I close the screen and then reopen it? import turtle win = turlte.Screen() Man = turtle.Turtle() for i in range(4): M

Solution 1:

If you use Tkinter with turtle.RawTurtle(canvas), you have access to all of Tkinter's functions, RawTurtle takes canvas as an argument, which is a tkinter canvas object. In this case, you can create a new tkinter.Toplevel, on which you can create a canvas, that you can use RawTurtle on. Something like this:

import turtle, random, time
from Tkinter import *
tk = Toplevel()
screen = Canvas(tk, width=500, height=500)
screen.pack()

t = turtle.RawTurtle(screen)

t.speed(0)
t.hideturtle()

defspiral(len, angle):
    for current inrange(1, int(len)):
        thetext = 'Currently turning '+str(a)+' degrees, then moving '+str(current)+' pixels'
        textitem = screen.create_text(-250, -250, text=thetext, anchor='nw', font=('Purisa', 12))
        t.forward(current)
        t.left(int(angle))
        screen.delete(textitem)
    t.up()
    t.goto(0, 0)
    t.down()


a, b = random.randint(-360, 360), 100
t.clear()
spiral(b, a)
tk.destroy()

print'Still running'
time.sleep(1)
print'Still running'

new = Toplevel()

newscreen = Canvas(new, width=500, height=500)
newscreen.pack()

t2 = turtle.RawTurtle(newscreen)
t2.fd(10)

As you can see, with RawTurtle, we can create and destroy tkinter windows, that contain canvases that function as turtle windows. As demonstrated in the first window, the other advantage is that you can create text and such as you would on a tkinter canvas otherwise. This code works in python 2.7, it may require some minor modification to work in python 3, I don't know. Anyway, in this example, we created and destroyed turtle windows at will. The main parts of the program are

tk = Toplevel()
screen = Canvas(tk, width=500, height=500)
screen.pack()

t = turtle.RawTurtle(screen)

which create a new turtle window, with t as the turtle, and

tk.destroy()

which will kill the turtle window without stopping the program. Hope this helps!

Post a Comment for "How Can I Close And Re-open Turtle Screen In Python"