[英]How to add a click event for images in Pygame?
我有以下代碼。 它基本上從文件夾應用程序及其子文件夾中獲取所有圖像。 我的問題是我試圖將click事件添加到所有圖像中以執行相同的操作。 基本上是“ exec("apps/" + apps[app_count] + "/app.py"
)“
# -*- coding: utf-8 -*-
from pygame import *
import os
import pygame
import time
import random
import sys
_image_library = {}
class SeedOS():
def home(self):
(width, height) = (240, 320)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Seed OS')
pygame.font.init()
Font30 = pygame.font.SysFont('Arial', 30)
WHITE = (255,255,255)
BLACK = (0,0,0)
screen.fill(WHITE)
apps = os.walk("apps").next()[1]
app_count = 0
icon_width = 15
icon_height = 0
max_width = 155
pygame.display.flip()
while True:
while app_count < len(apps):
print apps[app_count]
image = pygame.image.load("apps/" + apps[app_count] + "/app.png").convert()
screen.blit(image, (icon_width, icon_height))
icon_width+=70
if icon_width > max_width:
icon_width = 15
icon_height +=70
app_count += 1
time2 = time.strftime('%H:%M:%S')
pygame.display.flip()
pygame.draw.rect(screen,BLACK,(0,290,240,30))
clock = Font30.render(time2, False, WHITE)
screen.blit(clock,(60,288))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.quit()
phone = SeedOS()
phone.home()
這是檢查“ apps”文件夾中所有內容的代碼部分
while app_count < len(apps):
print apps[app_count]
image = pygame.image.load("apps/" + apps[app_count] + "/app.png").convert()
screen.blit(image, (icon_width, icon_height))
icon_width+=70
if icon_width > max_width:
icon_width = 15
icon_height +=70
app_count += 1
並附加每個文件夾中的所有圖像。 我希望在每個圖標上單擊,執行它的“ app.py”,因為在每個應用程序文件夾中都有兩個文件:“ app.png”和“ app.py”。
您可以在apps
列表中添加每個圖像的坐標,然后將這些坐標與pygame.mouse.get_pos()
方法一起使用:
while True:
while app_count < len(apps):
print apps[app_count]
apps[app_count] = (apps[app_count], icon_width, icon_height) # Adding coordinates to the list
image = pygame.image.load("apps/" + apps[app_count][0] + "/app.png").convert() # Adding an index to find the image in the tuple
screen.blit(image, (icon_width, icon_height))
icon_width+=70
if icon_width > max_width:
icon_width = 15
icon_height +=70
app_count += 1
time2 = time.strftime('%H:%M:%S')
pygame.display.flip()
pygame.draw.rect(screen,BLACK,(0,290,240,30))
clock = Font30.render(time2, False, WHITE)
screen.blit(clock,(60,288))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # MOUSEBUTTONLEFT
for a in apps:
if a[1] < pygame.mouse.get_pos()[0] < a[1]+IMAGEWIDTH and a[2] < pygame.mouse.get_pos()[1] < a[2] + IMAGEHEIGHT:
# Instruction to launch ("apps/" + a[0] + "/app.py")
您要做的就是定義圖標的寬度和高度pygame.Surface.get_size()
如果每個應用程序都不相同,可以使用pygame.Surface.get_size()
進行操作),並用正確的語法替換最后一行。 在Windows上,您可以使用:
os.system("apps\\"+a[0]+"\\app.py") # of course you should import os first
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.