Pygame เป็นไลบรารีมัลติมีเดียสำหรับ Python ใช้สร้างเกมและแอปพลิเคชันมัลติมีเดีย ในบทความนี้ เราจะดูวิธีใช้โมดูล pygame เพื่อวาดรูปภาพบนหน้าจอ โดยคำนึงถึงความสูง ความกว้าง และตำแหน่งในหน้าต่าง pygame
ในโปรแกรมด้านล่าง เราเริ่มต้นโมดูล pygame แล้วกำหนดโหมดและ Caption สำหรับรูปภาพ ต่อไปเราโหลดรูปภาพและกำหนดพิกัด ฟังก์ชัน screen.blit จะวาดหน้าจอ ในขณะที่ While Loop จะคอยฟังการคลิกจบเกม
ตัวอย่าง
import pygame
pygame.init()
w = 300; h = 300
screen = pygame.display.set_mode((w, h))
pygame.display.set_caption('Tutorialspoint Logo')
TPImage = pygame.image.load("E:\\Python3\\tutorialspoint.png").convert()
# coordinates of the image
x = 10; y = 20;
screen.blit(TPImage, (x, y))
# paint screen one time
pygame.display.flip()
running = True
while (running):
# loop listening for end of game
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# loop over, quite pygame
pygame.quit()
ผลลัพธ์
การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ −
