【问题标题】:Turtle module crashes when using counter on while loop在 while 循环中使用计数器时 Turtle 模块崩溃
【发布时间】:2021-09-18 01:29:25
【问题描述】:
from turtle import *
import tkinter

r = 0
shapes = [shape("square"), shape("turtle"), shape("triangle")]

def hello():
    while True:
        right(100)
        forward(100)
        left(100)
        r +=1
        
        

hello()
tkinter.mainloop()

每当我删除 r +=1 时,它都可以正常工作。但我一添加它,它就崩溃了。我为什么要使用计数器的主要原因是因为最初我的代码看起来像这样:

from turtle import *
import tkinter

r = 0
shapes = [shape("square"), shape("turtle"), shape("triangle")]

def hello():
    while True:
        right(r)
        forward(r)
        left(r)
        r +=1
        
        

hello()
tkinter.mainloop()

但这会让程序崩溃得更快,这很有趣。有人遇到类似问题吗?

【问题讨论】:

  • “崩溃”是什么意思?您收到错误消息吗?
  • 不,窗口只是关闭了。我想你可以称之为“崩溃”。感谢 tkinter 模块,我可以随时保持窗口打开和关闭。但是柜台阻碍了我这样做
  • 这是因为引发了异常“UnboundLocalError: local variable 'r' referenced before assignment”。在hello() 的开头添加global r。顺便说一句,您应该使用 after() 而不是 while 循环。
  • 最好将r = 0 移动到函数内部,因为它不会在其他任何地方使用。它不需要是全局的。

标签: python python-3.x tkinter turtle-graphics python-turtle


【解决方案1】:

除了r 未被声明为global 之外,您的程序还有几个问题。首先,这是一个无限循环,因此您的计数器将永远不会被检查。其次,它不必要地导入 tkinter。让我们重新编写你的代码,让它不再永远循环,而是在海龟在你的窗口外游荡时返回 counter 的值:

from turtle import *

def hello():
    counter = 0

    width, height = window_width(), window_height()

    while -width/2 < xcor() < width/2 and -height/2 < ycor() < height/2:
        right(counter)
        forward(counter)
        left(counter)

        counter += 1

    return counter

print(hello())

mainloop()

输出

> python3 test.py
31
>

【讨论】:

    猜你喜欢
    • 2014-05-14
    • 1970-01-01
    • 2012-06-19
    • 2021-07-09
    • 1970-01-01
    • 2018-08-27
    • 2019-12-18
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多