[Python][Pygame]使用pygame写一个小型的GUI(一):标签和按钮

本文介绍了如何使用Python的Pygame库创建一个简单的GUI,包括按钮和标签组件。详细讲解了初始化窗口、监听鼠标事件、定义不同组件以及主循环等关键步骤,同时提供了代码示例,展示了一个包含按钮和标签的交互界面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用pygame写一个小型的GUI

先看效果

按钮和标签(字体,字体颜色,背景颜色以及移动到按钮上时的字体颜色,背景颜色均可任意修改)
按钮和标签(字体,字体颜色,背景颜色均可任意修改)
鼠标移动到按钮上时:
当鼠标移动到按钮上时

需要

  • python3.x
  • pygame

安装python

直接去官网下载,安装时一路Next即可.注意安装3.x版本的.

安装pygame

Ctrl+R :打开命令提示符

输入:

pip install pygame

等待安装完毕.

测试pygame是否安装成功
在命令提示符中输入:

python

然后输入:

import pygame

如果弹出类似于:

pygame 2.0.1 (SDL 2.0.14, Python 3.7.0)
Hello from the pygame community. https://www.pygame.org/contribute.html

说明已经安装成功了.
如果是这样:

ModuleNotFoundError: No module named 'pygame'

百度寻找原因,这里不再赘述.

写库

直接上代码:

import pygame	 # 导入pygame库
comp = []	 # 储存组件


def init(size, title):	 # 初始化,明确窗口的大小和标题
    pygame.init()
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption(title)
    return screen	# 返回screen后面用


def listening():	 # 监听鼠标事件
    x, y = pygame.mouse.get_pos()	 # 获取鼠标位置
    for m in comp:	 # 遍历组件
        if m[-1][0] <= x <= m[-1][0]+m[-1][2] and m[-1][1] <= y <= m[-1][3]+m[-1][1]:	 # 判断鼠标是否在组件上
            m[-2] = True
        else:
            m[-2] = False


def button(size, position, font, font_color, background,
           click_f_color, click_background, func, edge=5, width=0, title="Button"):	 # 添加按钮组件
    if_click = False
    crash_rect = [0, 0, 0, 0]	 # “碰撞体”,鼠标在这个范围算碰撞
    return ["bu", title, position, font, background, font_color,
            size, width, click_f_color, click_background, func, edge, if_click, crash_rect]


def label(size, position, font, font_color, background=0, title="Label",
          edge=5, width=0):	 # 标签组件
    if_click = False
    crash_rect = [0, 0, 0, 0]
    return ["la", title, position, font, background, font_color, size, width, edge, if_click, crash_rect]


def register_cp(way):	 # 注册组件
    comp.append(way)


def text_objects(text, font, color):	 # 定义文字
    text_surface = font.render(text, True, color)
    return text_surface, text_surface.get_rect()


def display(scr, com):	 # 显示组件
    for n in com:
        if n[0] == "bu":    # 如果是按钮
            if n[12]:   # 判断是否点击
                large_text = pygame.font.Font(n[3], n[6])
                text_surf, text_rect = text_objects(n[1], large_text, n[8])
                text_rect.center = n[2]
                pygame.draw.rect(scr, n[9], (text_rect.left - n[11],
                                             text_rect.top - n[11],
                                             text_rect.width + n[11] * 2,
                                             text_rect.height + n[11] * 2), n[7])
                scr.blit(text_surf, text_rect)	 # 把字刻在屏幕上
                n[13] = text_rect
            else:
                large_text = pygame.font.Font(n[3], n[6])
                text_surf, text_rect = text_objects(n[1], large_text, n[5])
                text_rect.center = n[2]
                pygame.draw.rect(scr, n[4], (text_rect.left-n[11],
                                             text_rect.top-n[11],
                                             text_rect.width+n[11]*2,
                                             text_rect.height+n[11]*2), n[7])
                scr.blit(text_surf, text_rect)
                n[13] = text_rect

        if n[0] == "la":    # 如果是标签 'freesansbold.ttf', 115
            large_text = pygame.font.Font(n[3], n[6])
            text_surf, text_rect = text_objects(n[1], large_text, n[5])
            text_rect.center = n[2]
            if n[4] != 0:
                pygame.draw.rect(scr, n[4], (text_rect.left-n[-3],
                                             text_rect.top-n[-3],
                                             text_rect.width+n[-3]*2,
                                             text_rect.height+n[-3]*2), n[-2])
            scr.blit(text_surf, text_rect)


def run(scr, background):	 # 主循环
    go_on = True
    while go_on:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:	 # 如果点击关闭窗口,则循环结束
                go_on = False
        scr.fill(background)	 # 设置屏幕背景色
        display(scr, comp)
        listening()
        pygame.display.update()	 # 更新屏幕


程序方面

自由发挥,
前面图里的效果:

import main


def say_hello():
    print("Hello, World!")


scr = main.init((600, 600), "Test")
la1 = main.label(30, (100, 100), "freesansbold.ttf", (255, 255, 255),
                 (55, 55, 55), "Hello, World!")
bu1 = main.button(30, (300, 300), "freesansbold.ttf", (255, 255, 255),
                  (55, 55, 55), (255, 255, 255), (155, 155, 155), say_hello)

main.register_cp(la1)
main.register_cp(bu1)

main.run(scr, (0, 0, 0))


注意前面两个文件要放在同一个文件夹里.
不然,

import main

会出错.
后期会陆续添加一些组件,例如输入框,进度条等.

Thank for reading!

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值