You have to check if the mouse cursor is in the rectangular area of the slider. Use pygame.Rect
objects and collidepoint()
to test if the mouse cursor is on the slider. The position of the mouse cursor can be get with pygame.mouse.get_pos()
.
slider_rect1 = pygame.Rect(600, 300, 210, 10)
slider_rect2 = pygame.Rect(600, 400, 210, 10)
mouse_pos = pygame.mouse.get_pos()
if slider_rect1.collidepoint(mouse_pos) and pygame.mouse.get_pressed()[0] != 0:
# [...]
if slider_rect2.collidepoint(mouse_pos) and pygame.mouse.get_pressed()[0] != 0:
# [...]
See also How to detect when a rectangular object, image or sprite is clicked
Function saved_sim
:
def saved_sim():
slider1 = 600
slider2 = 600
#size_of_gas_cloud = 400
slider_rect1 = pygame.Rect(600, 300, 210, 10)
slider_rect2 = pygame.Rect(600, 400, 210, 10)
running = True
while running:
menu.fill(BACKGROUND_COLOR)
title = Label(menu, "Editting features for simulation", 1, font_title, BLACK, 330, 30)
Sub_heading = Label(menu, "Please edit the features using sliders before selecting a location", 1, font_para, BLACK, 5, 100)
mouse_pos = pygame.mouse.get_pos()
if slider_rect1.collidepoint(mouse_pos) and pygame.mouse.get_pressed()[0] != 0:
# collision detection also needed here
slider1 = pygame.mouse.get_pos()[0] - 5
if slider1 < 600:
slider1 = 600
if slider1 > 800:
slider1 = 800
if slider_rect2.collidepoint(mouse_pos) and pygame.mouse.get_pressed()[0] != 0:
# collision detection also needed here
slider2 = pygame.mouse.get_pos()[0] - 5
if slider2 < 600:
slider2 = 600
if slider2 > 800:
slider2 = 800
pygame.draw.rect(menu, BLACK, slider_rect1)
pygame.draw.rect(menu, RED, Rect(slider1, 300, 10, 10))
pygame.draw.rect(menu, BLACK, slider_rect2)
pygame.draw.rect(menu, RED, Rect(slider2, 400, 10, 10))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…