【问题标题】:Python turtle error on closing screen - code from How to Think Like a Computer Scientist: Learning with Python 3关闭屏幕上的 Python 乌龟错误 - 来自如何像计算机科学家一样思考的代码:使用 Python 3 学习
【发布时间】:2017-10-08 10:51:19
【问题描述】:

当我运行这段代码时

import turtle
import time

def show_poly():
    try:
        win = turtle.Screen()
        tess = turtle.Turtle()
        n = int(input("How many sides do you want in your polygon?"))
        angle = 360 / n
        for i in range(n):
            tess.forward(10)
            tess.left(angle)
        time.sleep(3)
    finally:
        win.bye()

show_poly()
show_poly()
show_poly()

我得到的第一个电话工作正常而不是我得到这个错误

Traceback(最近一次调用最后一次): 文件“/home/turte.py”,第 19 行, 在 show_poly() 中

文件“/home/turte.py”,第 8 行,在 show_poly 中 tess = turtle.Turtle()

文件“/usr/lib/python3.5/turtle.py”,第 3816 行,在 init 中 可见=可见)

文件“/usr/lib/python3.5/turtle.py”,第 2557 行,在 init 中 self._update()

文件“/usr/lib/python3.5/turtle.py”,第 2660 行,在 _update self._update_data()

文件“/usr/lib/python3.5/turtle.py”,第 2646 行,在 _update_data 中 self.screen._incrementudc()

文件“/usr/lib/python3.5/turtle.py”,第 1292 行,在 _incrementudc

饲养终结者龟.终结者

如果我了解问题所在,即使我关闭了最后一个屏幕,我也无法创建新屏幕。 我运行 python 3.5

【问题讨论】:

  • 您的代码在此处引发SyntaxError
  • 对不起,这是一个缩进错误。此外,它适用于 Python3.4

标签: python python-3.5 turtle-graphics


【解决方案1】:

turtle.Screen() 返回的对象旨在成为单例,因此您的代码正在积极应对模块设计。根据the docs,您应该在应用程序中使用RawTurtle 的实例。

import turtle
import time
import tkinter as tk


def show_poly():
    try:
        n = int(input("How many sides do you want in your polygon?"))
        angle = 360 / n
        root = tk.Tk()
        canvas = turtle.ScrolledCanvas(root)
        canvas.pack(expand=True, fill='both')
        tess = turtle.RawTurtle(canvas)
        for i in range(n):
            tess.forward(10)
            tess.left(angle)
        time.sleep(3)
    finally:
        root.destroy()


show_poly()
show_poly()
show_poly()

【讨论】:

  • 感谢您的解释。我从文档中阅读了单例的东西,但是自从我在“如何像计算机科学家一样思考:使用 Python 3 学习”中找到了这段代码后,我不明白问题出在哪里。此外,它适用于 python 3.4,但不适用于 3.5 或 2.7。
  • 作者的选择很糟糕。如果Screen() 的返回值是一个单例,我会考虑它在.bye() 未定义之后的行为。它可能会偶然起作用,但您不应该依赖它。我发现 tkinter 在最近的版本中有点严格,还有一些其他未记录的技巧不再起作用。
【解决方案2】:

另一种方法是在turtle 中工作并尽可能避免使用tkinter。在下面的解决方案中,我们没有破坏窗口并创建一个新窗口,而是简单地清除它并重新绘制:

from turtle import Turtle, Screen
from time import sleep

def show_poly(turtle):
    n = 0

    while n < 3:
        try:
            n = int(input("How many sides do you want in your polygon? "))
        except ValueError:
            pass

    angle = 360 / n

    for _ in range(n):
        turtle.forward(50)
        turtle.left(angle)

    sleep(3)
    turtle.clear()

window = Screen()

tess = Turtle()

show_poly(tess)
show_poly(tess)
show_poly(tess)

window.bye()

这也应该与 Python 2.7 和 Python 3 兼容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-22
    • 2018-01-25
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多