使用tkinter实现音乐播放器
python实现
使用tkinter实现音乐播放器可以让用户在图形化界面下方便地播放音乐。以下是一个简单的实现步骤:
import pygame
import tkinter as tk
import os.path
from tkinter import filedialog
import os
class VoiceRecognitionGUI:
def __init__(self, master):
self.master = master
master.geometry('400x200')
# 控制台输出
self.label = tk.Label(master, text="请选择音乐文件")
self.label.place(x=100, y=45)
self.button = tk.Button(master, text="选择音频",bg="lightblue", command=self.choose_file)
self.button.place(x=20, y=45)
self.play_button = tk.Button(master, text="播放", bg="lightblue",command=self.play_music)
self.play_button.place(x=130, y=80)
self.stop_button = tk.Button(master, text="停止",bg = "OrangeRed", command=self.stop_music)
self.stop_button.place(x=290, y=80)
def choose_file(self):
# 弹出文件选择窗口
file_path = filedialog.askopenfilename(
filetypes=[("Audio files", "*.wav;*.mp3;*.ogg")])
self.label.config(text="已选择文件: " + f"{os.path.basename(file_path)}")
self.music_file = file_path
def play_music(self):
pygame.mixer.init()
self.playing = False
if not self.playing:
# 载入音乐文件
pygame.mixer.music.load(self.music_file)
# 播放音乐
pygame.mixer.music.play()
self.playing = True
def stop_music(self):
if self.playing:
# 停止音乐
pygame.mixer.music.stop()
self.playing = False
if __name__ == '__main__':
root = tk.Tk()
gui = VoiceRecognitionGUI(root)
root.mainloop()
界面展示