pygame里面并沒有封裝好的按鈕和輸入框, 以下是我親測(cè)有效且非常易上手的代碼
- 生成輸入框
創(chuàng)建draw.py文件如下
import pygame
import os
class InputBox:
def __init__(self, rect: pygame.Rect = pygame.Rect(100, 100, 140, 32)) -> None:
"""
rect,傳入矩形實(shí)體,傳達(dá)輸入框的位置和大小
"""
self.boxBody: pygame.Rect = rect
self.color_inactive = pygame.Color('lightskyblue3') # 未被選中的顏色
self.color_active = pygame.Color('dodgerblue2') # 被選中的顏色
self.color = self.color_inactive # 當(dāng)前顏色,初始為未激活顏色
self.active = False
self.text = '' # 輸入的內(nèi)容
self.done = False
self.font = pygame.font.Font(None, 32)
def dealEvent(self, event: pygame.event.Event):
if(event.type == pygame.MOUSEBUTTONDOWN):
if(self.boxBody.collidepoint(event.pos)): # 若按下鼠標(biāo)且位置在文本框
self.active = not self.active
else:
self.active = False
self.color = self.color_active if(
self.active) else self.color_inactive
if(event.type == pygame.KEYDOWN): # 鍵盤輸入響應(yīng)
if(self.active):
if(event.key == pygame.K_RETURN):
'''在鍵盤輸入的同時(shí),self.text的值也在隨之改變,其實(shí)并不需要通過按回車來記錄值'''
print(self.text)
# self.text=''
elif(event.key == pygame.K_BACKSPACE):
self.text = self.text[:-1]
else:
self.text += event.unicode
def draw(self, screen: pygame.surface.Surface):
txtSurface = self.font.render(
self.text, True, self.color) # 文字轉(zhuǎn)換為圖片
'''注意,輸入框的寬度實(shí)際是由這里max函數(shù)里的第一個(gè)參數(shù)決定的,改這里才有用'''
width = max(200, txtSurface.get_width()+10) # 當(dāng)文字過長(zhǎng)時(shí),延長(zhǎng)文本框
self.boxBody.w = width
screen.blit(txtSurface, (self.boxBody.x+5, self.boxBody.y+5))
pygame.draw.rect(screen, self.color, self.boxBody, 2)
為了測(cè)試以上代碼,創(chuàng)建main.py如下:
import pygame
from pygame import Surface
from pygame.constants import QUIT
from draw import InputBox
WIDTH = 600
HEIGHT = 500
FPS = 120
screen: Surface = None # 窗口實(shí)例
clock = None # 時(shí)鐘實(shí)例
textFont = None # 字體
def pygameInit(title: str = "pygame"):
"""初始化 pygame"""
pygame.init()
pygame.mixer.init() # 聲音初始化
pygame.display.set_caption(title)
global screen, clock, textFont # 修改全局變量
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
if __name__ == "__main__":
pygameInit("輸入框示例")
inputbox = InputBox(pygame.Rect(100, 20, 140, 32)) # 輸入框
running = True
while running:
clock.tick(FPS) # 限制幀數(shù)
screen.fill((255, 255, 255)) # 鋪底
for event in pygame.event.get():
if event.type == QUIT:
running = False
inputbox.dealEvent(event) # 輸入框處理事件
inputbox.draw(screen) # 輸入框顯示
pygame.display.flip()
pygame.quit()
效果如下:文章來源:http://www.zghlxwxcb.cn/news/detail-509182.html
- 生成按鈕
創(chuàng)建Button.py
class Button:
NORMAL=0
MOVE=1
DOWN=2
def __init__(self,x,y,text,imgNormal,imgMove=None,imgDown=None,callBackFunc=None,font=None,rgb=(0,0,0)):
"""
初始化按鈕的相關(guān)參數(shù)
:param x: 按鈕在窗體上的x坐標(biāo)
:param y: 按鈕在窗體上的y坐標(biāo)
:param text: 按鈕顯示的文本
:param imgNormal: surface類型,按鈕正常情況下顯示的圖片
:param imgMove: surface類型,鼠標(biāo)移動(dòng)到按鈕上顯示的圖片
:param imgDown: surface類型,鼠標(biāo)按下時(shí)顯示的圖片
:param callBackFunc: 按鈕彈起時(shí)的回調(diào)函數(shù)
:param font: pygame.font.Font類型,顯示的字體
:param rgb: 元組類型,文字的顏色
"""
#初始化按鈕相關(guān)屬性
self.imgs=[]
if not imgNormal:
raise Exception("請(qǐng)?jiān)O(shè)置普通狀態(tài)的圖片")
self.imgs.append(imgNormal) #普通狀態(tài)顯示的圖片
self.imgs.append(imgMove) #被選中時(shí)顯示的圖片
self.imgs.append(imgDown) #被按下時(shí)的圖片
for i in range(2,0,-1):
if not self.imgs[i]:
self.imgs[i]=self.imgs[i-1]
self.callBackFunc=callBackFunc #觸發(fā)事件
self.status=Button.NORMAL #按鈕當(dāng)前狀態(tài)
self.x=x
self.y=y
self.w=imgNormal.get_width()
self.h=imgNormal.get_height()
self.text=text
self.font=font
#文字表面
self.textSur=self.font.render(self.text,True,rgb)
def draw(self,destSuf):
dx=(self.w/2)-(self.textSur.get_width()/2)
dy=(self.h/2)-(self.textSur.get_height()/2)
#先畫按鈕背景
if self.imgs[self.status]:
destSuf.blit(self.imgs[self.status], [self.x, self.y])
#再畫文字
destSuf.blit(self.textSur,[self.x+dx,self.y+dy])
def colli(self,x,y):
#碰撞檢測(cè)
if self.x<x<self.x+self.w and self.y<y<self.y+self.h:
return True
else:
return False
def getFocus(self,x,y):
#按鈕獲得焦點(diǎn)時(shí)
if self.status==Button.DOWN:
return
if self.colli(x,y):
self.status=Button.MOVE
else:
self.status=Button.NORMAL
def mouseDown(self,x,y):
'''通過在這個(gè)函數(shù)里加入返回值,可以把這個(gè)函數(shù)當(dāng)做判斷鼠標(biāo)是否按下的函數(shù),而不僅僅是像這里只有改變按鈕形態(tài)的作用'''
if self.colli(x,y):
self.status = Button.DOWN
def mouseUp(self):
if self.status==Button.DOWN: #如果按鈕的當(dāng)前狀態(tài)是按下狀態(tài),才繼續(xù)執(zhí)行下面的代碼
self.status=Button.NORMAL #按鈕彈起,所以還原成普通狀態(tài)
if self.callBackFunc: #調(diào)用回調(diào)函數(shù)
return self.callBackFunc()
為了使用這個(gè)類,創(chuàng)建main.py如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-509182.html
import pygame
from Button import Button
# 初始化pygame
pygame.init()
winSur = pygame.display.set_mode([300, 300])
# 加載按鈕圖片
'''這里需要自己準(zhǔn)備三張按鈕的圖片,分別對(duì)應(yīng)正常形態(tài),鼠標(biāo)懸停形態(tài),鼠標(biāo)按下形態(tài),把圖片放在和此文件同一目錄下即可''''
surBtnNormal = pygame.image.load("./btn_normal.png").convert_alpha()
surBtnMove = pygame.image.load("./btn_move.png").convert_alpha()
surBtnDown = pygame.image.load("./btn_down.png").convert_alpha()
#按鈕使用的字體
btnFont = pygame.font.SysFont("lisu", 40)
# 按鈕的回調(diào)函數(shù)
def btnCallBack():
print("我被按下了")
# 創(chuàng)建按鈕
btn1 = Button(30, 50, "按鈕測(cè)試", surBtnNormal, surBtnMove, surBtnDown, btnCallBack,btnFont,(255,0,0))
btn2 = Button(30, 150, "", surBtnNormal, surBtnMove, surBtnDown, btnCallBack,btnFont)
# 游戲主循環(huán)
while True:
mx, my = pygame.mouse.get_pos() # 獲得鼠標(biāo)坐標(biāo)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.MOUSEMOTION: # 鼠標(biāo)移動(dòng)事件
# 判斷鼠標(biāo)是否移動(dòng)到按鈕范圍內(nèi)
btn1.getFocus(mx, my)
btn2.getFocus(mx, my)
elif event.type == pygame.MOUSEBUTTONDOWN: # 鼠標(biāo)按下
if pygame.mouse.get_pressed() == (1, 0, 0): #鼠標(biāo)左鍵按下
btn1.mouseDown(mx,my)
btn2.mouseDown(mx, my)
elif event.type == pygame.MOUSEBUTTONUP: # 鼠標(biāo)彈起
btn1.mouseUp()
btn2.mouseUp()
pygame.time.delay(16)
winSur.fill((0, 0, 0))
#繪制按鈕
btn1.draw(winSur)
btn2.draw(winSur)
#刷新界面
pygame.display.flip()
到了這里,關(guān)于【pygame】創(chuàng)建輸入框和按鈕的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!