【问题标题】:Python Turtle shows an error when window is closed关闭窗口时 Python Turtle 显示错误
【发布时间】:2020-06-26 06:49:18
【问题描述】:

我在 python 中有一个问题。 我正在制作一个名为“Stars”的小程序,其中包含超过 29 行的海龟图形。 当我在程序完成之前关闭海龟窗口时,它会显示错误。这不是什么大问题,但是当我将它转换为exe(使用pyinstaller)然后在程序完成之前关闭窗口时,会弹出一个警告框并说:“执行脚本星失败”。

有没有比将每一行都放在 try-except 中更好的方法来忽略这一点?:

try:
   #each line of code
except:
   pass

提前致谢

当它有帮助时:我在 Python 3.7.7 和 Windows 10 中

代码如下:

from turtle import *
shape("turtle")
width(2)
color("gold")
begin_fill()
for _ in range(5):
        forward(100)
        right(2 * 360/5)
        forward(100)
        left(360/5)
end_fill()
penup()
goto(0, 200)
write("STAR", font = ("Arial", 50), align = "center")
goto(-200, -200)
pendown()
stamp()
forward(50)
stamp()
forward(50)
stamp()
forward(50)
stamp()
forward(50)
stamp()
forward(50)
stamp()
forward(50)
stamp()
forward(50)
exitonclick()

这里是 pyinstaller 命令:

pyinstaller --noconfirm --onefile --noconsole  "C:/Users/jeeva/Desktop/Tanmay_new/python/Python_turtle_answers/Stars.py"

【问题讨论】:

  • 我真的建议发布这 29 行,以便了解发生了什么
  • @Anwarvic 感谢您的建议。我编辑了问题。

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


【解决方案1】:

您可以像try..except 所说的那样在整行上阻塞,如下所示:

try:
    # all 29 lines of your code:
except:
    pass

它会工作得很好!


但是,我真的建议将您的程序安排成不同的功能;喜欢:

  1. 创建海龟的函数:

    def create_turtle():
        shape("turtle")
        width(2)
        color("gold")
    
  2. 绘制和填充星形的功能:

    def draw_fill_star():
        begin_fill()
        for _ in range(5):
                forward(100)
                right(2 * 360/5)
                forward(100)
                left(360/5)
        end_fill()
    
  3. 写“星”字的功能:

    def write_start():
        penup()
        goto(0, 200)
        write("STAR", font = ("Arial", 50), align = "center")
    
  4. 写印章的功能:

    def write_stamps():
        goto(-200, -200)
        pendown()
        stamp()
        forward(50)
        stamp()
        forward(50)
        stamp()
        forward(50)
        stamp()
        forward(50)
        stamp()
        forward(50)
        stamp()
        forward(50)
        stamp()
        forward(50)
        exitonclick()
    
  5. 最后,一个函数来执行它们。

    def execute():
        create_turtle()
        draw_fill_star()
        write_start()
        write_stamps()
    

现在,您可以将函数包装到 try...except 块中,如下所示:

try:
    execute()
except Terminator:
    print("Program has been terminated")

【讨论】:

  • 感谢您的回答。我从没想过您可以将所有代码行放在 1 try-except 中,而不是将每一行放在不同的行中。
  • 很高兴我能帮上忙 :)
  • 谢谢,但你能解释一下除了终结者是什么意思吗?
  • 表示你在程序自行终止之前就已经终止了
  • @Anwarvic 非常感谢
猜你喜欢
  • 2021-12-24
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多