How can I create a clickable button in graphics.py window?

55 Views Asked by At

I'm trying to make a game, and have the start screen have a button that you can click to start playing the game.

I tried the clickPoint=getMouse() but I am unsure how to incorporate it. Can I use the while True statement or would I have to use something else?

1

There are 1 best solutions below

0
On

Theoretically zella graphics is created using tkinter which has tkinter.Button(..., command=function) but zella graphics works different than tkinter and it can make problem to use tkinter.Button() directly with zella graphics.

At this moment the only idea is to use while True with getMouse() (or checkMouse()) and check if you clicked inside button's rectangle.

from graphics import *

win = GraphWin("My Buttons", 200, 200)

c = Rectangle(Point(50,50), Point(150,100))
c.setFill('Red')
c.draw(win)

while True:
    clickPoint = win.getMouse()
    
    if (c.getP1().getX() <= clickPoint.getX() <= c.getP2().getX()
        and c.getP1().getY() <= clickPoint.getY() <= c.getP2().getY()):
            print('Red Button Clicked')
            break

win.close()

If you have many buttons then you could create new class Button (using `Rectangle) with function which checks if it was clicked.

class Button(Rectangle):

    def isClicked(self, point):
        return (self.getP1().getX() <= point.getX() <= self.getP2().getX()
                and self.getP1().getY() <= point.getY() <= self.getP2().getY())

or shorter

class Button(Rectangle):

    def isClicked(self, point):
        return (self.p1.x <= point.x <= self.p2.x
                and self.p1.y <= point.y <= self.p2.y)

and now if needs shorter code

from graphics import *

class Button(Rectangle):

    def isClicked(self, point):
        #return (self.getP1().getX() <= point.getX()<= self.getP2().getX()
        #        and self.getP1().getY() <= point.getY() <= self.getP2().getY()
    
        return (self.p1.x <= point.x <= self.p2.x
                and self.p1.y <= point.y <= self.p2.y)
      
# --- main ---
        
win = GraphWin("My Buttons", 200, 200)

c = Button(Point(50,50), Point(150,100))
c.setFill('Red')
c.draw(win)

d = Button(Point(50,100), Point(150,150))
d.setFill('Green')
d.draw(win)

while True:
    clickPoint = win.getMouse()
    
    if c.isClicked(clickPoint):
       print('Red Button Clicked')
       break

    if d.isClicked(clickPoint):
       print('Green Button Clicked')
       break

win.close()