python學習之pygame畫圖模塊
cmd中執行命令:pip install pygame
如果已經安裝,則會告知“Requirement already satisified”。
代碼
import pygamepygame.init()screen = pygame.display.set_mode([640, 480])running = Truewhile running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = Falsepygame.quit()執行:
生成一個640*480大小的黑色窗口。
代碼
import pygame, syspygame.init()screen = pygame.display.set_mode([640,480])screen.fill([255,255,255]) # fill screen with white pygame.draw.circle(screen, [255,0,0],[100,100], 30, 0) # draw red circlepygame.display.flip()running = Truewhile running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = Falsepygame.quit()執行

代碼screen.fill([255,255,255])將畫布設置為了白色。
注意:除了pygame可以畫出很多形狀,如aalines,arc,circle,ellipse,lines,polygon…且可以對其大小顏色等屬性進行設置。
可以用大量很小的圓或矩形形成一個像素點。
import pygame, sysimport math pygame.init()screen = pygame.display.set_mode([640,480])screen.fill([255, 255, 255])running = Truewhile running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False for x in range(0, 640): y = int(math.sin(x/640.0 * 4 * math.pi) * 200 + 240) # sine wave formula # draw the wave using small rectangles pygame.draw.rect(screen, [0,0,0],[x, y, 1, 1], 1) # x, y is the location of each rectangle # in the wave pygame.display.flip() pygame.time.delay(30)pygame.quit()執行

在屏幕上畫圖是一種方法,另一種是將照片添加在屏幕上。
import pygame, syspygame.init()screen = pygame.display.set_mode([640,480])screen.fill([255, 255, 255])my_ball = pygame.image.load("beach_ball.png") # load the image from a file screen.blit(my_ball, [50, 50]) # draw or 'blit' it to the screenpygame.display.flip()running = Truewhile running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = Falsepygame.quit()在新的位置畫出圖形,再把原來的圖形擦掉。
import pygame, syspygame.init()screen = pygame.display.set_mode([640,480])screen.fill([255, 255, 255])my_ball = pygame.image.load('beach_ball.png')screen.blit(my_ball,[50, 50]) # draw the beach ballpygame.display.flip()pygame.time.delay(2000)screen.blit(my_ball, [150, 50]) # draw it again, somewhere else# "erase" the first beach ballimagepygame.draw.rect(screen, [255,255,255], [50, 50, 90, 90], 0) pygame.display.flip()running = Truewhile running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = Falsepygame.quit()
新聞熱點
疑難解答