添加按钮 Python graphics.py window

Adding button to Python graphics.py window

我有一个项目是用 python 制作一个简单的闯关游戏。我在图形上制作按钮时遇到问题 window。

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)

在这里,如何将这些矩形制作成代表动作的按钮"Left",&"Right"??

下面是一个红色左键、绿色右键和一个"Exit"按钮退出程序的简单解决方案。我重新排列了代表按钮的矩形,使 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()

如果您点击红色或绿色按钮,您会在 window 的中心打印 "left" 或 "right",否则不会出现文本: