移动Python graphics.py对象

2 投票
1 回答
10695 浏览
提问于 2025-04-18 12:32

我正在尝试在Python图形中同时移动两个物体(这似乎是指John Zelle的graphics.py),然后在一个循环中重复这个动作。但是当我尝试循环时,形状就消失了。我该怎么解决这个问题呢?

def main():
    win = GraphWin('Lab Four', 400, 400)
    c = Circle(Point(100, 50), 40)
    c.draw(win)
    c.setFill('red')
    s = Rectangle(Point(300, 300), Point(350, 350))
    s.draw(win)
    s.setFill('blue')
    s.getCenter()
    while not c.getCenter() == Circle(Point(400, 50), 40):
        c.move(10, 0)
        s.move(-10, 0)
    win.getMouse
    while not (win.checkMouse()):
        continue
    win.close()

1 个回答

0

你的代码有几个明显的问题:你把圆心的点对象和圆对象进行了比较,其实应该比较点对象;另外,在调用win.getMouse()的时候,你忘记加括号了。下面的修改解决了这些问题:

from graphics import *

WIDTH, HEIGHT = 400, 400
RADIUS = 40

def main():
    win = GraphWin('Lab Four', WIDTH, HEIGHT)

    c = Circle(Point(100, 50), RADIUS)
    c.draw(win)
    c.setFill('red')

    s = Rectangle(Point(300, 300), Point(350, 350))
    s.draw(win)
    s.setFill('blue')

    while c.getCenter().getX() < WIDTH - RADIUS:
        c.move(10, 0)
        s.move(-10, 0)

    win.getMouse()
    win.close()

main()

我没有直接比较圆心的点,而是简单地检查了它的X坐标,因为它是水平移动的。

撰写回答