我们将使用pygame的mixer组件来播放音效,使用tk来实现ui。
让我们开始吧!
导入必要的库:
import tkinter
import pynput
from pygame import mixer
编写一个函数,使得按下一个按钮的时候通过传参的方法来实现出声。
def ikun(key, type):
# 路径问题
f1 = open("../主界面/path.txt", "r", encoding="UTF-8")
main_path = f1.readline()
f1.close()
if type == "开启特殊键位的音效":
if str(key) == "'j'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\鸡.mp3").play()
elif str(key) == "'n'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\你.mp3").play()
elif str(key) == "'t'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\太.mp3").play()
elif str(key) == "'m'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\美.mp3").play()
elif str(key) == "'b'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\bebe.mp3").play()
elif str(key) == "'w'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\唱.mp3").play()
elif str(key) == "'a'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\跳.mp3").play()
elif str(key) == "'s'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\rap.mp3").play()
elif str(key) == "'d'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\篮球.mp3").play()
elif str(key) == "'q'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\music.mp3").play()
elif str(key) == "'g'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\你干嘛.mp3").play()
elif str(key) == "'k'":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\坤.mp3").play()
elif type == "开启所有键位的音效":
mixer.Sound(f"{main_path}\\键盘音效\\音效库\\鸡.mp3").play()
编写主要的ui并运行:
def main(types=None):
"""
主菜单界面
:param types: mxt-7的经典tk递归操作
:return: None
"""
global screen
if types is None: # 主菜单UI设计
screen = tkinter.Tk() # 窗口初始化
screen.title("键盘音效") # 设置标题
screen.geometry("500x300+250+120") # 设置窗口大小与初始化位置
screen.iconbitmap("../主界面/ironmouse.ico") # 设置窗口图标
screen.resizable(width=False, height=False) # 禁止改变窗口大小!!!!!!
font1 = ("SimSun", 20) # 设置一种字体
# 控件摆放
tkinter.Canvas(screen, height=300, width=500, bg='grey').place(x=0, y=0)
tkinter.Button(screen, text="开启特殊键位的音效", font=font1, command=lambda: main(types="开启特殊键位的音效"),
bg='#777777', activebackground='#777777').place(x=30, y=30)
tkinter.Button(screen, text="开启所有键位的音效", font=font1, command=lambda: main(types="开启所有键位的音效"),
bg='#777777', activebackground='#777777').place(x=30, y=80)
screen.mainloop() # 保持窗口显示
elif types == "开启特殊键位的音效" or types == "开启所有键位的音效":
pynput.keyboard.Listener(on_press=lambda key: ikun(key, types)).start()
screen.iconify()
if __name__ == "__main__":
mixer.init()
main()
运行后有两种模式,一种是让你的键盘每一个键都“坤”叫,另一种是某些按钮有特定的声音
本项目所有素材已经上传,有任何问题可联系作者。