2014-01-14 101 views
1

我仍然是Python的noob,現在我只是開始使用我的GUI。現在我在屏幕上有一堆元素,我想知道如何在一個元素上註冊點擊,然後用它來改變點擊的元素和另一個元素。把它放到上下文中,我正在做一個燈開關。我會發布我所擁有的代碼,因爲它不是太笨重。如何點擊一個元素,然後用它來改變另一個元素

#Import pygame lib 
import pygame 
from pygame.locals import * 

#Initialize the game 
pygame.init() 
width, height = 640, 480 
screen = pygame.display.set_mode((width, height)) 

#Load images 
switchOn = pygame.image.load("resources/img/switchOn.png") 
switchOff = pygame.image.load("resources/img/switchOff.png") 
bulbOn = pygame.image.load("resources/img/bulbOn.png") 
bulbOff = pygame.image.load("resources/img/bulbOff.png") 

#Loop 
while 1: 
    #clear screen before drawing again 
    screen.fill(0) 
    #draw the screen elements 
    screen.blit(bulbOff, (50,50)) 
    screen.blit(switchOff, (300,250)) 
    #update the screen 
    pygame.display.flip() 
    #loop the events 
    for event in pygame.event.get(): 
     #check if event is X button 
     if event.type==pygame.QUIT: 
      pygame.quit() 
      exit(0) 

回答

1

要,比如說註冊點擊一個按鈕,你需要使用pygame.Rect.collidepoint(http://pygame.org/docs/ref/rect.html#pygame.Rect.collidepoint),並檢查當前鼠標的位置是我們的按鈕的矩形內。

在僞代碼:

check for events 
    if event is mouseclick 
     if button.rect.collidepoint(button, mouse_pos) 
      # player clicked, so... 
      do something 

創建一個可點擊的按鈕是沒有太大的麻煩,說實話,但如果你在Python和pygame的新它可能是一個有點粗糙。

相關問題