【pygame】创建输入框和按钮

pygame里面并没有封装好的按钮和输入框, 以下是我亲测有效且非常易上手的代码

  1. 生成输入框
    创建draw.py文件如下
import pygame
import os

class InputBox:
    def __init__(self, rect: pygame.Rect = pygame.Rect(100, 100, 140, 32)) -> None:
        """
        rect,传入矩形实体,传达输入框的位置和大小
        """
        self.boxBody: pygame.Rect = rect
        self.color_inactive = pygame.Color('lightskyblue3')  # 未被选中的颜色
        self.color_active = pygame.Color('dodgerblue2')  # 被选中的颜色
        self.color = self.color_inactive  # 当前颜色,初始为未激活颜色
        self.active = False
        self.text = '' # 输入的内容
        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)):  # 若按下鼠标且位置在文本框
                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):  # 键盘输入响应
            if(self.active):
                if(event.key == pygame.K_RETURN):
                '''在键盘输入的同时,self.text的值也在随之改变,其实并不需要通过按回车来记录值'''
                    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)  # 文字转换为图片
            '''注意,输入框的宽度实际是由这里max函数里的第一个参数决定的,改这里才有用'''
        width = max(200, txtSurface.get_width()+10)  # 当文字过长时,延长文本框
        self.boxBody.w = width
        screen.blit(txtSurface, (self.boxBody.x+5, self.boxBody.y+5))
        pygame.draw.rect(screen, self.color, self.boxBody, 2)

为了测试以上代码,创建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  # 窗口实例
clock = None  # 时钟实例

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)  # 限制帧数
        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()

效果如下:
在这里插入图片描述

  1. 生成按钮
    创建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)):
        """
        初始化按钮的相关参数
        :param x: 按钮在窗体上的x坐标
        :param y: 按钮在窗体上的y坐标
        :param text: 按钮显示的文本
        :param imgNormal: surface类型,按钮正常情况下显示的图片
        :param imgMove: surface类型,鼠标移动到按钮上显示的图片
        :param imgDown: surface类型,鼠标按下时显示的图片
        :param callBackFunc: 按钮弹起时的回调函数
        :param font: pygame.font.Font类型,显示的字体
        :param rgb: 元组类型,文字的颜色
        """
        #初始化按钮相关属性
        self.imgs=[]
        if not imgNormal:
            raise Exception("请设置普通状态的图片")
        self.imgs.append(imgNormal)     #普通状态显示的图片
        self.imgs.append(imgMove)       #被选中时显示的图片
        self.imgs.append(imgDown)       #被按下时的图片
        for i in range(2,0,-1):
            if not self.imgs[i]:
                self.imgs[i]=self.imgs[i-1]
 
        self.callBackFunc=callBackFunc      #触发事件
        self.status=Button.NORMAL       #按钮当前状态
        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):
        #碰撞检测
        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):
        #按钮获得焦点时
        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):
    '''通过在这个函数里加入返回值,可以把这个函数当做判断鼠标是否按下的函数,而不仅仅是像这里只有改变按钮形态的作用'''
        if self.colli(x,y):
            self.status = Button.DOWN
 
    def mouseUp(self):
        if self.status==Button.DOWN:    #如果按钮的当前状态是按下状态,才继续执行下面的代码
            self.status=Button.NORMAL   #按钮弹起,所以还原成普通状态
            if self.callBackFunc:       #调用回调函数
                return self.callBackFunc()

为了使用这个类,创建main.py如下:

import pygame
 
from Button import Button
 
# 初始化pygame
pygame.init()
winSur = pygame.display.set_mode([300, 300])
 
# 加载按钮图片
'''这里需要自己准备三张按钮的图片,分别对应正常形态,鼠标悬停形态,鼠标按下形态,把图片放在和此文件同一目录下即可''''
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)
 
# 按钮的回调函数
def btnCallBack():
    print("我被按下了")
 
 
# 创建按钮
btn1 = Button(30, 50, "按钮测试", surBtnNormal, surBtnMove, surBtnDown, btnCallBack,btnFont,(255,0,0))
btn2 = Button(30, 150, "", surBtnNormal, surBtnMove, surBtnDown, btnCallBack,btnFont)
 
# 游戏主循环
while True:
    mx, my = pygame.mouse.get_pos()  # 获得鼠标坐标
 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        elif event.type == pygame.MOUSEMOTION:  # 鼠标移动事件
            # 判断鼠标是否移动到按钮范围内
            btn1.getFocus(mx, my)
            btn2.getFocus(mx, my)
 
        elif event.type == pygame.MOUSEBUTTONDOWN:  # 鼠标按下
            if pygame.mouse.get_pressed() == (1, 0, 0): #鼠标左键按下
                btn1.mouseDown(mx,my)
                btn2.mouseDown(mx, my)
 
        elif event.type == pygame.MOUSEBUTTONUP:  # 鼠标弹起
            btn1.mouseUp()
            btn2.mouseUp()
 
    pygame.time.delay(16)
    winSur.fill((0, 0, 0))
    #绘制按钮
    btn1.draw(winSur)
    btn2.draw(winSur)
    #刷新界面
    pygame.display.flip()
pygame是一个用于创建游戏和其他图形界面应用的Python库。在pygame中设置按钮通常涉及到以下几个步骤: ### 步骤一:导入必要的模块 ```python import pygame as pg from pygame.locals import * ``` ### 步骤二:初始化pygame ```python pg.init() ``` ### 步骤三:设置屏幕大小、背景色、标题等 ```python screen = pg.display.set_mode((800, 600)) # 设置窗口大小 pg.display.set_caption("我的游戏") # 窗口标题 background_color = (255, 255, 255) # 背景颜色 ``` ### 步骤四:创建按钮对象 按钮可以看作一个矩形区域,并为其添加文本。 ```python def create_button(x, y, width, height, text): button_rect = Rect(x, y, width, height) font = pg.font.Font(None, 32) # 创建字体对象 text_surface = font.render(text, True, (0, 0, 0), background_color) # 渲染文本 text_rect = text_surface.get_rect(center=button_rect.center) return button_rect, text_surface, text_rect # 示例按钮 button_rect, text_surface, text_rect = create_button(300, 300, 100, 50, "点击这里") ``` ### 步骤五:事件处理和绘制按钮 ```python running = True while running: for event in pg.event.get(): if event.type == QUIT: running = False elif event.type == MOUSEBUTTONDOWN and button_rect.collidepoint(event.pos): # 检查鼠标点击是否落在按钮上 print("按钮被点击了") screen.fill(background_color) screen.blit(text_surface, text_rect) # 绘制文本到屏幕上 pg.draw.rect(screen, (0, 0, 0), button_rect, 2) # 添加边框以便更清晰显示按钮 pg.display.flip() # 更新显示内容 pg.quit() ``` ### 相关问题: 1. 如何改变按钮的颜色? 2. 如何让按钮响应不同的操作(如悬停和点击时改变样式)? 3. 怎样检测按钮内部的点击位置并执行相应的函数?
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值