python 漂亮的花框音乐盒子flower frame box music player

python 花框音乐盒子flower frame box music box player by lixingqiu李兴球

"""这是一个用海龟画图模块和pygame的混音模块制作的简易音乐播放器。
作者:李兴球,日期:2018/8/26"""

from turtle import *

def init_screen():
    """初始化屏幕"""
    screen = Screen()
    screen.setup(width,height)
    screen.bgpic("舞台.png")
    screen.title(gametitle)
    screen.delay(0)
    return screen

def init_mixer():
    """初始化混音器,注意在函数内部导入的模块的作用范围"""
    have_pygame = False
    try:
        import pygame
        pygame.mixer.init()
        have_pygame = True
    except:
        pygame = None
    return have_pygame ,pygame
    
class Button(Turtle):
    """按钮类,每个按钮有两张图片,自带音乐"""
    
    def __init__(self,costume_list,x,y,music,width,height):
        Turtle.__init__(self,visible=False)
        self.penup()
        self.costume_list = costume_list     # 造型列表
        self.costume_index = 0               # 造型初始索引号
        self.shape(self.costume_list[self.costume_index]) # 设置造型为索引为0的图
        self.goto(x,y)
        self.width = width
        self.height = height
        self.left = x - width/2     # 左边x坐标
        self.right = x + width/2    # 右边x坐标
        self.top  = y + height/2    # 上边y坐标
        self.bottom = y - height/2  # 下边y坐标
        self.music = music         
        self.showturtle()
        self.onclick(self.play)     # 单击按钮调用play方法
        
    def play(self,x,y):
        """先停止音乐再播放音乐"""
        pygame.mixer.music.stop()           # 停止正在播放的音乐
        pygame.mixer.music.load(self.music)
        screen.title(gametitle + ",正在播放:" + self.music  + " 作者:李兴球")
        pygame.mixer.music.play(-1,0)    # -1表示循环播放,0表示从头开始播放
        
    def onmousemove(self,event):
        """判断鼠标指针是否在按钮坐标范围内"""
        mouse_x = event.x - width/2      # 转换为海龟坐标系的x坐标
        mouse_y = height/2 - event.y     # 转换为海龟坐标系的y坐标
        # 以下代码判断鼠标指针是否在按钮矩形范围内
        if mouse_x > self.left and mouse_x < self.right \
           and mouse_y > self.bottom and mouse_y < self.top:
            self.costume_index = 1
        else:
            self.costume_index = 0
        self.shape(self.costume_list[self.costume_index])

You must log in to read the rest of this article. Please log in or register as a user.