Domanda

I am attempting to apply the getMouse() function to a specific part of the window, instead of the whole thing. I need the block that is clicked in to change color if it is 'rect1'. However if any other block is clicked, nothing should happen. I have attached the portion of my code which I feel relates to this in case anyone can be of any assistance.

#draw the grid 
for j in range (6):
    for i in range(6):
        sq_i = Rectangle(Point(20 + (40*i), 20 + (40*j)),
                         Point(60 + (40*i),60 + (40*j)))
        sq_i.draw(window)
        sq_i.setFill('white')
        sq_i.setOutline('grey')

#wait for a click 
window.getMouse ()

#turn the alotted region red
rect1 = Rectangle(Point(20 + (40*1), 20 + (40*1)),
                         Point(60 + (40*1), 60 + (40*1)))
rect1.setOutline('black')
rect1.draw(window)
rect1.setFill('brown')

#if the mouse is clicked in rect1, change the block color to black 
while window.getMouse() in rect1:
    rect1.setFill('black')
È stato utile?

Soluzione

First off, you need to understand what window.getMouse() in rect1 does. Python's in operator works by turning a in b into the method call b.__contains__(a). Unfortunately, the Rectangle class doesn't have a __contains__ method. This your immediate problem.

So, you need to use a different test. I suggest using Python's chained comparison operators to do the bounds checking yourself (there doesn't seem to be any library support for this in the graphics module):

mouse = window.getMouse()
if rect1.p1.x < mouse.x < rect1.p2.x and rect1.p1.y < mouse.y < rect1.p2.y
    rect1.setFill("black")

Note that I've changed the while loop for an if statement. If you want to repeatedly test mouse clicks until one hits the rectangle, you probably want to loop on while True and then break if the tested condition is true:

while True:
    mouse = window.getMouse()
    if rect1.p1.x < mouse.x < rect1.p2.x and rect1.p1.y < mouse.y < rect1.p2.y
        rect1.setFill("black")
        break
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top