0

I am creating a program which generates a random list of songs, and has a function such that if a user wants to save a song from the random generated list, the user should click the button next to it. Then the user can print the songs he/she saved on a new window, but the function for that in my code seems to only print the saved songs in the terminal and I only get empty window. How can I implement this correctly?

This the code:

from tkinter import *
from PIL import ImageTk, Image
import random


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

a = [
    '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():
    global alist
    alist = []
    if genre.get() == 'Favorite':
        # alist.clear()
        top = Toplevel()
        top.title('Your Playlist')
        for i, title in enumerate(random.sample(a, k=10)):
            myLabel = Label(top, text=title, font='times 12', anchor=W)
            myLabel.grid(column=2, columnspan=2, sticky=W + E, row=i)

            Button(top,
                   text=str(i + 1) + ".",
                   border=5,
                   padx=5,
                   pady=5,
                   command=lambda title=title: alist.append(title)
                   ).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():
    global alist
    blist = []
    global myLabel
    for song in alist:
        if song not in alist:
            blist.append(song)

    top = Toplevel()
    top.title('Your Playlist')
    for i, title in enumerate(blist):
        myLabel = Label(top, text=title, font='times 12', anchor=W)
        myLabel.grid(column=2, columnspan=2, sticky=W + E, row=i)

    print(alist)

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()
1
  • 2
    your code is long - where do you try to display it in other window? Commented Jan 9, 2021 at 14:24

1 Answer 1

1

I thing all your problem is because you use silimar names of variables alist and blist and finally you used wrong list in code

for song in alist:
    if song not in alist:   # <-- should be `blist`
        blist.append(song)

Should be

for song in alist:
    if song not in blist:   # <-- should be `blist`
        blist.append(song)

In your version you get from alist and compare with the same alist so it always gives False and it never add to blist


Eventually you could use set() to recognize new titles.


But I think you have other problem - you try to add to blist only new items but before for-loop you use

blist = []

so your list empty and there is no need to check what to move to blist because you can move everthing

blist = alist

If you want to keep previous items then you shouldn't assing blist = [] and you should keep it as global list.


EDIT

My full version with other changes: better names for funtions and variables, all function before rest of code, etc.

PEP 8 -- Style Guid for Python Code

import tkinter as tk  # PEP8: `import *` is not preferred
import random

# --- functions ---

def show_generated_list():
    global generated_list
    
    generated_list = []
    
    if genre.get() == 'Favorite':
    
        # generated_list.clear()
        top = tk.Toplevel()
        top.title('Your Playlist')
        
        for i, title in enumerate(random.sample(a, k=10)):
        
            my_label = tk.Label(top, text=title, font='times 12', anchor='w')  # PEP8: `lower_case_names` for variales
            my_label.grid(column=2, columnspan=2, sticky='we', row=i)

            tk.Button(top,
                   text=str(i+1) + ".",
                   border=5,
                   padx=5,
                   pady=5,
                   command=lambda title=title: generated_list.append(title)
                   ).grid(column=0, row=i)
                   
        tk.Button(top, text='close window', command=top.destroy).grid(row=12, column=1, columnspan=3, sticky='we')


def show_my_playlist():  # verb for function name, noun for variable
    global generated_list    # PEP8: all `global` at the beginning
    #global my_label # PEP8: `lower_case_names` for variales  # you don't need it
    
    for song in generated_list:
        if song not in my_playlist:
            my_playlist.append(song)

    top = tk.Toplevel()
    top.title('Your Playlist')
    
    for i, title in enumerate(my_playlist):
        my_label = tk.Label(top, text=title, font='times 12', anchor='w')
        my_label.grid(column=2, columnspan=2, sticky='we', row=i)

    print(generated_list)

# --- main ---

# - data -

a = [
    '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'
]

options = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Favorite"
]

generated_list = []  # created at start to make sure it always exists
my_playlist = []     # created at start to make sure it always exists
    
- gui -

root = tk.Tk()
root.title('UMIND')
#root.geometry('')  # empty geometry is useless

genre = tk.StringVar()
genre.set('From what genre?')

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

generate_btn = tk.Button(root, text="Generate Playlist", command=show_generated_list)
generate_btn.grid(row=2, column=1, ipadx=30, ipady=10, padx=15, pady=15)

playlist_btn = tk.Button(root, text="My Playlist", command=show_my_playlist)
playlist_btn.grid(row=3, column=0, ipadx=30, ipady=10, padx=15, pady=15)

root.columnconfigure(0, weight=1)

row_con = [drop, generate_btn, playlist_btn]

for row_num in range(len(row_con)):
    root.rowconfigure(row_num, weight=1)

root.mainloop()
Sign up to request clarification or add additional context in comments.

6 Comments

How would I retain the contents or the items of my_playlist, because when I rerun the program my_playlist resets and loses its contents or items that were previously added?
my version keeps previous content. I create my_playlist = [] only at start and later I don't use my_playlist = [] in function show_my_playlist
when I close the program then open and run it again, and click My Playlist button it only returns an empty window
now I see what is your problem. Python will not keep it for you - like in any other program (ie. Word, Excel) you have to save it on disk and read it again when you restart program. You may use normal txt file or something more useful like csv file or json file or module pickle
I will try one of those, because I just tried using sqlite but I can not comprehend it yet
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.