Python海龟绘图程序在IDLE中可以运行,但在其他情况下无法运行。

4
我使用Python中的turtle创建了一个简单的按钮程序。虽然可能有些杂乱,但在IDLE中完美运行。然而,尝试在没有IDLE的情况下加载它时,它只会绘制两个按钮,然后退出程序。我查阅代码,但没有找到原因。
以下是我认为问题出现的地方(最后几行):
def main():
    onscreenclick(Button.clicked,1)

main()

但我并不完全确定。为了保险起见,这是完整的程序。

from turtle import *
bgcolor('skyblue')
penup()
left(90)
speed(0)
hideturtle()
buttonlist = []

class Button:
  x_click = 0
  y_click = 0
  def __init__(self, x, y, size, color, text, fontsize, fixvalue):
    self.x = x
    self.y = y
    self.size = size
    self.color = color
    self.text = text
    self.fontsize = fontsize
    self.fixvalue = fixvalue
  def showButton(self):
    goto(self.x , self.y)
    pendown()
    fillcolor(self.color)
    begin_fill()
    for i in range(4):
      forward(self.size)
      right(90)
    end_fill()
    penup()
    goto((self.x+self.size/2),self.y+self.fixvalue)
    right(90)
    write(self.text, move=False, align="center", font=("Arial", self.fontsize, "normal"))
    left(90)
  def hideButton(self):
    goto(self.x, self.y)
    fillcolor('skyblue')
    pencolor('skyblue')
    pendown()
    begin_fill()
    for i in range(4):
      forward(self.size)
      right(90)
    end_fill()
    penup()
    pencolor('black')
  def checkClick(self):
    if self.x < Button.x_click:
      if Button.x_click < (self.x+self.size):
        if self.y < Button.y_click:
          if Button.y_click < (self.y+self.size):
            return 1

  def clicked(x, y):
    Button.x_click = x
    Button.y_click = y

    if home_1.checkClick() == 1:
      home_1.hideButton()
    if home_2.checkClick() == 1:
      home_2.hideButton()

home_1 = Button(10,10,100,'red','←',45,20)
home_2 = Button(-50,-50,50,'blue','Hello!',10,15)
Button.showButton(home_1)
Button.showButton(home_2)

def main():
    onscreenclick(Button.clicked,1)

main()

我希望有一个解决方案。
祝好。

2
请使用代码块添加您的代码,而不是链接到某个 Web 服务,并提供 MCVE - albert
1
我强烈建议你停止使用 from turtle import *,而是改用 import turtle 并通过 turtle.penup() 等方式使用函数。现在到处重复写相同的东西可能会感觉很愚蠢,但是你未来的自己会感谢你的。导入许多这样的短名称将很快变得非常混乱。 - Markus Meskanen
或者例如 import turtle as tt,然后使用 tt.penup() 等。 - Terry Jan Reedy
2个回答

3

您说得没错,问题就在于main()函数中,尝试在结尾处添加turtle.mainloop()调用:

def main():
    onscreenclick(Button.clicked,1)
    mainloop()

main()

如果这对你没用,你也可以尝试使用turtle.done()函数,虽然我建议你先尝试mainloop()函数。
def main():
    onscreenclick(Button.clicked,1)
    done()

main()

0

turtle 基于 tkinter,后者基于 tcl/tk GUI 框架。Turtle 的 mainloop 最终调用 tcl 事件处理程序的 mainloop,该程序重复调用 tcl 的 update() 函数,处理挂起的事件并更新屏幕。tcl 的 mainloop 保持控制,直到明确退出,例如关闭 turtle 窗口。

IDLE 通过定期调用 tcl 的 update 而不阻塞 来帮助 turtle 和 tkinter 的开发和学习,因此可以(暂时)省略调用 mainloop,并通过在 IDLE Shell 中输入命令与正在工作的屏幕或屏幕进行交互。但是,在 IDLE 外部运行时需要添加回 mainloop。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接