添加按钮到Python graphics.py窗口

时间:2016-10-05 07:06:01

标签: python zelle-graphics

我有一个项目正在使用python进行简单的突破游戏。我在图形窗口上制作按钮时遇到问题。

from graphics import*
win = GraphWin("win",200,150)
def buttons():
    rectangle = Rectangle(Point(30,85),Point(60,55))
    rectangle2 = Rectangle(Point(170,85),Point(140,55))
    rectangle.setFill("blue")
    rectangle2.setFill("blue")
    rectangle.draw(win)
    rectangle2.draw(win)

在这里,我如何将这些矩形作为代表“左”运动的按钮,& “右” ??

1 个答案:

答案 0 :(得分:1)

下面是一个简单的解决方案,用于红色左按钮,绿色右按钮和退出程序的“退出”按钮。我重新排列了代表按钮的矩形,使得P1是左下角,P2是右上角。这简化了测试,以查看点击的点是否在按钮内。 (您可以使代码更复杂,以消除此假设。)

from graphics import *

WINDOW_WIDTH, WINDOW_HEIGHT = 200, 150

win = GraphWin("Simple Breakout", WINDOW_WIDTH, WINDOW_HEIGHT)

def buttons():
    left = Rectangle(Point(25, 55), Point(55, 85))  # points are ordered ll, ur
    right = Rectangle(Point(145, 55), Point(175, 85))
    quit = Rectangle(Point(85, 116), Point(115, 146))

    left.setFill("red")
    right.setFill("green")
    text = Text(Point(100, 133), "Exit")
    text.draw(win)

    left.draw(win)
    right.draw(win)
    quit.draw(win)

    return left, right, quit

def inside(point, rectangle):
    """ Is point inside rectangle? """

    ll = rectangle.getP1()  # assume p1 is ll (lower left)
    ur = rectangle.getP2()  # assume p2 is ur (upper right)

    return ll.getX() < point.getX() < ur.getX() and ll.getY() < point.getY() < ur.getY()

left, right, quit = buttons()

centerPoint = Point(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
text = Text(centerPoint, "")
text.draw(win)

while True:
    clickPoint = win.getMouse()

    if clickPoint is None:  # so we can substitute checkMouse() for getMouse()
        text.setText("")
    elif inside(clickPoint, left):
        text.setText("left")
    elif inside(clickPoint, right):
        text.setText("right")
    elif inside(clickPoint, quit):
        break
    else:
        text.setText("")

win.close()

如果单击红色或绿色按钮,则会在窗口中央打印“左”或“右”,否则不会显示任何文本:

enter image description here