Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将数据附加到pickle_Python_Python 3.x_Tkinter_Pickle - Fatal编程技术网

在python中将数据附加到pickle

在python中将数据附加到pickle,python,python-3.x,tkinter,pickle,Python,Python 3.x,Tkinter,Pickle,我正在创建一个程序,该程序生成一个随机歌曲列表,并具有这样一个功能:如果用户希望从随机生成的列表中保存一首歌曲,则用户应单击旁边的按钮。然后用户可以打印他/她保存在新窗口上的歌曲,然后我使用pickle添加一个函数,这样,如果用户关闭并重新运行程序,以前保存的项目将保留并可以重新打印。但是一个错误,我怎样才能正确地实现它呢 代码如下: from tkinter import * import tkinter as tk from PIL import ImageTk, Image import

我正在创建一个程序,该程序生成一个随机歌曲列表,并具有这样一个功能:如果用户希望从随机生成的列表中保存一首歌曲,则用户应单击旁边的按钮。然后用户可以打印他/她保存在新窗口上的歌曲,然后我使用pickle添加一个函数,这样,如果用户关闭并重新运行程序,以前保存的项目将保留并可以重新打印。但是一个错误,我怎样才能正确地实现它呢

代码如下:

from tkinter import *
import tkinter as tk
from PIL import ImageTk, Image
import random
import pickle
from tkinter import messagebox

alternative_music = ['Smells Like Teen Spirit - Nirvana',
                     'Love will tear us apart - Joy Division',
                     'Radio Free Europe - R.E.M.',
                     'Blue Monday - New Order',
                     'How Soon is Now? - The Smiths',
                     'Once in a Lifetime - Talking Heads',
                     'Teen Age Riot - Sonic Youth',
                     'Blister in the Sun - Violent Femmes',
                     'Jeremy - Pearl Jam',
                     'Monkey Gone to Heaven - Pixies',
                     'Under the Bridge - Red Hot Chili Peppers',
                     'Black Hole Sun - Soundgarden',
                     'Closer - Nine Inch Nails',
                     'Losing My Religion - R.E.M.',
                     'Wonderwall - Oasis',
                     'Just like Heaven - The Cure',
                     'Cannonball - The Breeders',
                     'Come As You Are - Nirvana',
                     'Loser - Beck',
                     'Creep - Radiohead',
                     'Bela Lugosis Dead - Bauhaus',
                     'Personal Jesus - Depeche Mode',
                     'Song 2 - Blur',
                     'The Killing Moon - Echo and the Bunnymen',
                     'Sunday Bloody Sunday - U2',
                     'Common People - Pulp',
                     'There Is a Light That Never Goes Out - The Smiths',
                     'Running Up That Hill (A Deal With God) - Kate Bush',
                     'Its The End of the World As We Know It (And I Feel Fine) - R.E.M.',
                     '1979 - The Smashing Pumpkins',
                     'Waiting Room - Fugazi',
                     'Lovesong - The Cure',
                     'Alive - Pearl Jam',
                     'Radio, Radio - Elvis Costello & The Attractions',
                     'All Apologies - Nirvana',
                     'Atmosphere - Joy Division',
                     'Here Comes Your Man - Pixies',
                     'Paranoid Android - Radiohead',
                     f"There She Goes - The La's",
                     'Everlong - Foo Fighters',
                     'Buddy Holly - Weezer',
                     'Plush - Stone Temple Pilots',
                     'Enjoy the Silence - Depeche Mode',
                     'This Charming Man - The Smiths',
                     'Would? - Alice in Chains',
                     'The One I Love - R.E.M.',
                     'Touch Me, Im Sick - Mudhoney',
                     'Head Like a Hole - Nine Inch Nails',
                     'Bastards of Young - The Replacements',
                     'Burning Down the House - Talking Heads']


def show_generated_list():
    global generated_list

    generated_list = []

    if genre.get() == "Alternative Music":
        top = tk.Toplevel()
        top.title(genre.get() +' Play list')
        windowWidth = top.winfo_reqwidth()
        windowHeight = top.winfo_reqheight()
        positionRight = int(top.winfo_screenwidth() / 1.7 - windowWidth / 2)
        positionDown = int(top.winfo_screenheight() / 4 - windowHeight / 2)
        top.geometry("+{}+{}".format(positionRight, positionDown))

        # Info Box
        messagebox.showinfo("You can save the song", "You can save each song \n by clicking the button beside it")

        for i, title in enumerate(random.sample(alternative_music, k=10)):
            my_label = tk.Label(top, text=title, font=('Garamond ',14),
                                anchor='w', bg="#7dd0b6", highlightbackground='#000000',
                                highlightthickness=10, bd=0, borderwidth=0)
            my_label.grid(column=2, columnspan=2, sticky='we', row=i, pady=2)
            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)

def show_my_playlist():
    global generated_list
    global my_playlist
    global my_img
    global bg_lbl

    for song in generated_list:
        if song not in my_playlist:
            my_playlist.append(song)


    filename = "my_playlist2.txt"
    with open(filename, 'a+') as fp:
        pickle.dump(my_playlist, fp)
        # pickle.dump(q, fp)

    top = tk.Toplevel()
    top.title('Your Playlist')
    top.geometry("500x500")
    windowWidth = top.winfo_reqwidth()
    windowHeight = top.winfo_reqheight()
    positionRight = int(top.winfo_screenwidth() / 1.7 - windowWidth / 2)
    positionDown = int(top.winfo_screenheight() / 4 - windowHeight / 2)
    top.geometry("+{}+{}".format(positionRight, positionDown))
    my_img = ImageTk.PhotoImage(Image.open("tkimageviewer/imgbg2.png"))
    bg_lbl =Label(top, image=my_img)
    bg_lbl.place(x=0, y=0, relwidth=1, relheight=1)

    data = []
    with open(filename, 'rb') as fr:
        try:
            while True:
                data.append(pickle.load(fr))
        except EOFError:
            pass

    for i, title in enumerate(data):
        my_label = tk.Label(top, text=title, font=("Courier New",14), anchor='w', borderwidth=0)
        my_label.grid(column=2, columnspan=2, sticky='we', row=i, pady=(18,0))




genre_options = [
    "Alternative Music",
    # "Classical and Opera Music",
    # "Country and Folk",
    # "Dance and EDM",
    # "Reggae and R&B/Soul",
    # "Worship and Gospel and New Age",
    # "Pop Music",
    # "Songs people  like to listen to"
]

generated_list = []
my_playlist = []
my_quote_list = []
root = Tk()
root.title('UMIND')
root.iconbitmap('Ricon.ico')
root.geometry('')
root.config(bg='light blue')
windowWidth = root.winfo_reqwidth()
windowHeight = root.winfo_reqheight()
positionRight = int(root.winfo_screenwidth() / 8 - windowWidth / 2)
positionDown = int(root.winfo_screenheight() / 4 - windowHeight / 2)
root.geometry("+{}+{}".format(positionRight, positionDown))
playlist_gen_btn = PhotoImage(file="tkimageviewer/playlis_gen_btn.png")
my_qts_btn = PhotoImage(file="tkimageviewer/my_qts_btn.png")
my_playlist_btn = PhotoImage(file="tkimageviewer/my_playlist_btn.png")
genre = StringVar()
genre.set('From what Genre?')

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

generate_btn = tk.Button(root, image=playlist_gen_btn, command=show_generated_list, borderwidth=0)
generate_btn.grid(row=2, column=1, padx=15, pady=15)

playlist_btn = tk.Button(root, image=my_playlist_btn, command=show_my_playlist, borderwidth=0)
playlist_btn.grid(row=3, column=0, padx=15, pady=15)


root.mainloop()
这是我得到的错误:

  File "C:\PycharmProjects\pythonProject\picklepractice.py", line 112, in show_my_playlist
    pickle.dump(my_playlist, fp)
TypeError: write() argument must be str, not bytes
似乎使用
“ab+”
就可以了

输出:

[1, 2, 3]
[1, 2, 3]

用于保存pickle数据的任何文件都需要以二进制模式打开,例如,
'ab+'
而不是
'a+'
[1, 2, 3]
[1, 2, 3]