如何在 Python 中关闭并重新打开 Turtle Screen [英] How can I close and re-open Turtle Screen in Python

查看:110
本文介绍了如何在 Python 中关闭并重新打开 Turtle Screen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能指导我吗?画完正方形后,如何关闭屏幕再重新打开?

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):
    Man.fd(100)
    Man.right(90)

推荐答案

如果您将 Tkinter 与 turtle.RawTurtle(canvas) 一起使用,您可以访问 Tkinter 的所有功能,RawTurtlecanvas 作为参数,它是一个 tkinter 画布对象.在这种情况下,您可以创建一个新的 tkinter.Toplevel,您可以在其上创建一个画布,您可以在其上使用 RawTurtle.像这样:

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()

def spiral(len, angle):
    for current in range(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)

如您所见,使用 RawTurtle,我们可以创建和销毁 tkinter 窗口,其中包含用作海龟窗口的画布.如第一个窗口所示,另一个优点是您可以创建文本,就像在 tkinter 画布上一样.这段代码适用于 python 2.7,它可能需要一些小的修改才能在 python 3 中工作,我不知道.无论如何,在这个例子中,我们随意创建和销毁了海龟窗口.程序的主要部分是

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)

创建一个新的海龟窗口,以t作为海龟,而

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!

这篇关于如何在 Python 中关闭并重新打开 Turtle Screen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆