You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未导入音频文件时Pygame Mixer触发AttributeError的解决及提示功能实现

Fixing the AttributeError When Playing Without Selecting a File in Your Tkinter Music Player

Hey there! That crash happens because when you hit Play without picking a file first, your code tries to access window.filename—but that attribute only gets created after the user selects a file via open_file(). Without it, Python throws an AttributeError and stops the app cold. Let's fix this with a simple check and a user-friendly error popup.

Here's the updated code with the fix:

from tkinter import *
import tkinter as tk
from tkinter.ttk import *
from tkinter import filedialog
from tkinter.filedialog import askopenfile
import os
import pygame

# Function definitions
def start():
    global x
    x = 1
    pygame.mixer.init()
    file_select.place(x=200, y=10)
    file_play.place(x=280, y=10)
    volume_S.place(x=150, y=35)
    file_select.config(text="Open File", command=lambda:[open_file()])
    file_play.config(text="Play", command=lambda:[play_file()])

def open_file():
    # Added WAV file filter for better UX (optional but helpful)
    window.filename = filedialog.askopenfilename(
        initialdir="/", 
        title="Select a WAV file",
        filetypes=(("WAV files", "*.wav"), ("all files", "*.*"))
    )
    print(window.filename)

def play_file():
    # Check if a file has been selected before proceeding
    if hasattr(window, 'filename') and window.filename:
        pygame.mixer.music.load(window.filename)
        pygame.mixer.music.play()
        pygame.mixer.music.set_volume(0)
    else:
        # Show a popup alert instead of crashing
        tk.messagebox.showerror("Oops!", "Please select a WAV file first before hitting Play!")

def volumeset(self):
    pvolume = float(volume_S.get())
    pygame.mixer.music.set_volume(pvolume * 0.1)

# Print current file location (for debugging)
print(os.path.dirname(os.path.realpath(__file__)) )

# Initialize main window
window = tk.Tk()
window.geometry("796x448")
window.resizable(0, 0)

# Set up widgets
file_select = tk.Button(window, font=("Calibri", 10))
file_play = tk.Button(window, font=("Calibri", 10))
volume_S = tk.Scale(
    window, 
    variable=int, 
    command=volumeset, 
    orient="horizontal", 
    showvalue=False, 
    tickinterval=1, 
    to=10, 
    length=200
)

# Start the app
start()
window.mainloop()

Key changes I made:

  • Added a file check in play_file():
    • hasattr(window, 'filename') verifies that the attribute exists (so we don't get the AttributeError)
    • window.filename checks that the user didn't cancel the file dialog (which would leave filename empty)
  • Added a user-friendly popup:
    • tk.messagebox.showerror shows a clear error message instead of crashing the app, so users know exactly what to do
  • Improved file selection UX:
    • Updated the file dialog to prioritize WAV files (since this is a WAV player) and changed the title to be more specific

Now when you click Play without selecting a file, the app will show a popup instead of crashing—much better for user experience!

内容的提问来源于stack exchange,提问作者Yanbunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 12:32:48