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

Tkinter与Python列表:解决已保存歌曲无法在新窗口显示仅终端打印的问题

Fixing the Saved Songs Display in Your Tkinter Playlist App

Hey there! Let’s break down what’s going wrong with your app and get that saved songs window working properly. Your core idea is solid—just a few key bugs to iron out.

Key Problems in Your Current Code

  • Saved songs get erased every time you generate a new playlist: Your show() function starts with alist = [], which resets the list to empty every time you make a new random playlist. That’s why when you open "My Playlist", there’s nothing to show—your previous saves are gone.
  • Broken deduplication logic: In my_playlist(), the line if song not in alist is backwards. You’re checking if the song isn’t in the list you’re already looping through, so your blist always stays empty.
  • Poor variable scope & naming: Using alist globally works, but initializing it inside show() breaks persistence. Also, vague names like a and alist make the code harder to debug.

Fixed Code with Explanations

Here’s the revised code with comments pointing out the fixes:

from tkinter import *
import random

root = Tk()
root.title('UMIND')
root.geometry('')

# Initialize saved songs list ONCE outside any function—persists across app use
saved_songs = []

# Renamed to be more descriptive
song_database = [
    'Bruised and Scarred - Mayday Parade',
    'All Too Well - Taylor Swift',
    'Gravity - Sara Bareilles',
    'Perfectly Perfect - Simple Plan',
    'Welcome To The Black Parade - My Chemical Romance',
    'Everything Has Changed - Taylor Swift',
    'Champagne - Taylor Swift',
    'Piece of Your Heart - Mayday Parade',
    'Blame It On The Rain - He Is We',
    'Sad Song - We The Kings',
    'Give It All - He Is We',
    'Heavy - Linkin Park',
    'Ride - Twenty One Pilot',
    'One more light - Linkin Park',
    'Ride Home - Ben and Ben',
    'Leaves - Ben and Ben',
    'Fall - Ben and Ben',
    'Maybe the night - Ben and Ben',
    'Sunrise - Ben and Ben'
]

def show():
    if genre.get() == 'Favorite':
        top = Toplevel()
        top.title('Random Playlist')
        # Generate random sample without touching saved songs
        random_songs = random.sample(song_database, k=10)
        
        for i, title in enumerate(random_songs):
            myLabel = Label(top, text=title, font='times 12', anchor=W)
            myLabel.grid(column=2, columnspan=2, sticky=W + E, row=i)
            
            # Nested function to save songs with proper variable binding
            def save_this_song(song_title=title):
                # Avoid duplicates by checking before adding
                if song_title not in saved_songs:
                    saved_songs.append(song_title)
            
            Button(top, text=str(i + 1) + ".", border=5, padx=5, pady=5, command=save_this_song).grid(column=0, row=i)
        
        btn2 = Button(top, text='Close Window', command=top.destroy).grid(row=12, column=1, columnspan=3, sticky=W + E)

def my_playlist():
    top = Toplevel()
    top.title('Your Saved Playlist')
    
    # Show a friendly message if no songs are saved (no empty window!)
    if not saved_songs:
        Label(top, text="You haven't saved any songs yet!", font='times 12').grid(row=0, column=0, padx=20, pady=20)
        return
    
    # Display all saved songs directly (we already avoided duplicates when saving)
    for i, title in enumerate(saved_songs):
        myLabel = Label(top, text=title, font='times 12', anchor=W)
        myLabel.grid(column=2, columnspan=2, sticky=W + E, row=i)
    
    print(saved_songs)  # Keep terminal print for debugging if needed

options = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Favorite" ]
genre = StringVar()
genre.set('From what genre?')

drop = OptionMenu(root, genre, *options)
drop.grid(row=2, column=0, ipadx=20, ipady=10, padx=15, pady=15)

generate_btn = Button(root, text="Generate Playlist", command=show).grid(row=2, column=1, ipadx=30, ipady=10, padx=15, pady=15)
playlist_btn = Button(root, text="My Playlist", command=my_playlist).grid(row=3, column=0, ipadx=30, ipady=10, padx=15, pady=15)

Grid.columnconfigure(root, 0, weight=1)
row_con = [ drop, generate_btn, playlist_btn]
row_num = 0
for row in row_con:
    Grid.rowconfigure(root, row_num, weight=1)
    row_num += 1

root.mainloop()

What We Fixed & Why

  1. Persistent saved songs list: saved_songs is initialized once outside any function, so it doesn’t get reset when you generate new playlists.
  2. Fixed save button logic: The nested save_this_song function ensures each button saves the correct song, and we check for duplicates before adding to avoid clutter.
  3. No more empty saved playlist window: If the user hasn’t saved any songs, we show a clear message instead of a blank window.
  4. Cleaner variable names: Renamed vague variables like a and alist to song_database and saved_songs to make the code easier to read and maintain.

Bonus Ideas to Improve the App

  • Add a "Remove Song" button in the saved playlist window to let users delete entries.
  • Save saved_songs to a text/JSON file when the app closes, and load it on startup so songs persist across app sessions.
  • Add a genre filter for the other options (Monday/Tuesday etc.) if you plan to expand the app later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 03:37:42