当物体到达底部时关闭窗口

时间:2018-03-30 08:19:58

标签: python-3.6 zelle-graphics

我想显示一条消息,并在用户点击时关闭该窗口。这应该在圆到达窗口底部时发生。我不确定如何解决这个问题,一切正常,直到圆圈通过窗口底部,关闭的消息没有弹出,窗口没有关闭点击。我正在使用Zelle for Python的graphics.py图形库。我是Python的初学者,所以我的知识现在非常有限。我的代码如下:

from graphics import *

    def q2a():
        win = GraphWin("window",400,400)
        win.setCoords(0,0,400,400)
        win.setBackground("light grey")
        #drawing circle
        circle = Circle(Point(200,100),30)
        circle.setFill("red")
        circle.draw(win)
        #text
        message = Text(Point(200,200),"Click Anywhere to Begin")
        message.draw(win)
        #clicking
        while True:
            click = win.checkMouse()
            if click:
                message.undraw()
                while circle.getCenter().getY() < 170:
                    dy=1
                    dx = 0
                    dy *=-.01
                    circle.move(dx,dy)
        if circle.getCenter()== 0:
            circle.undraw()
            gameover = Text(Point(200,200),"Game Over - Click to Close")
            gameover.draw(win)
            win.checkMouse()
            win.close()


        q2a()

1 个答案:

答案 0 :(得分:0)

我相信这个问题比你做的更简单。一个问题是这是一个无限循环:

while circle.getCenter().getY() < 170:
    dy=1
    dx = 0
    dy *=-.01
    circle.move(dx,dy)

当圆圈的Y中心从100开始减小时,它总是小于170,所以这个循环永远不会结束,超出这一点的任何代码都不会被执行。让我们使用圆的半径30,这样圆圈就会停在窗口的底部。

另一个问题是,当您真正想要checkMouse()时,我相信您正在使用getMouse()。阅读有关这两个命令之间差异的文档。

这是我对你的代码的修改(有一些样式调整。)我把--0.01增量改为-0.1,因为我没有耐心!

from graphics import *

RADIUS = 30
HEIGHT, WIDTH = 400, 400
CENTER = Point(HEIGHT / 2, WIDTH / 2)

def q2a():
    win = GraphWin("window", HEIGHT, WIDTH)
    win.setCoords(0, 0, HEIGHT, WIDTH)
    win.setBackground("light grey")

    # drawing circle
    circle = Circle(Point(WIDTH / 2, 100), RADIUS)
    circle.setFill("red")
    circle.draw(win)

    # text
    message = Text(CENTER, "Click Anywhere to Begin")
    message.draw(win)

    # moving
    win.getMouse()
    message.undraw()

    while circle.getCenter().getY() > RADIUS:
        circle.move(0, -0.1)

    # end game
    circle.undraw()
    gameover = Text(CENTER, "Game Over - Click to Close")
    gameover.draw(win)
    win.getMouse()
    win.close()

q2a()
相关问题