2017-10-26 27 views
-3

私は、 "albums_data.py"と "album.py"の辞書をメインプログラムとして持っています。 メインプログラムのadd_one()関数を更新して、辞書の実際の状態を "albums_data.py"に書き込んで、辞書にいくつかのデータが追加された後に保存する必要があります(add_one()関数を使用)。辞書を.pyファイルに書き込む方法は?

import tkinter 
from albums_data import * 

root=tkinter.Tk() 
root.title("DICT example") 

#Functions 
def show_all(): 
    #clear the listbox 
    lb_music.delete(0,"end") 
    #iterate throught the keys and add to the listbox 
    for artist in albums: 
     lb_music.insert("end",artist) 

def show_one(): 
    artist=lb_music.get("active") #active is clicked field 
    album=albums[artist] 
    msg=artist+" - "+album 
    lbl_output["text"]=msg #Ready is replaced with msg 

def add_one(): 
    info=txt_input.get() 
    split_info=info.split(",") #list is created after is separated with "," 
    artist=split_info[0] 
    album=split_info[1] 
    albums[artist]=album 
    show_all() 
    txt_input.delete(0,"end") 

    #write to .py file (not worked to txt also) ->permission denied 
    f = open("albums_data.py","w") 
    f.write(str(albums)) 
    f.close() 


#GUI 
lbl_output=tkinter.Label(root,text="Ready") 
lbl_output.pack() 

txt_input=tkinter.Entry(root) 
txt_input.pack() 

lb_music=tkinter.Listbox(root) 
lb_music.pack() 

btn_show_all=tkinter.Button(root,text="Show all",command=show_all) 
btn_show_all.pack() 

btn_show_one=tkinter.Button(root,text="Show one",command=show_one) 
btn_show_one.pack() 

btn_add_one=tkinter.Button(root,text="Add one",command=add_one) 
btn_add_one.pack() 


root.mainloop() 
+0

あなたは明確な質問をする必要があります。 –

+5

これは非常に悪い考えです。代わりに[JSON](https://docs.python.org/3/library/json.html)を使用してください。 –

答えて

2

使用JSON album.py

albums= {} 
albums["Adele"]="21" 
albums["Michael Jackson"]="Thriler" 
albums["Lady Gaga"]="The Fame" 

albums_data.py:ここ

は、ソースコードです。

import json 

d = { "hello": "world" } 

with open('state.json', 'w') as f: 
    json.dump(d, f) 

with open('state.json', 'r') as f: 
    d2 = json.load(f) 

assert d == d2 
+2

どうして 'dump'と' load'の代わりに文字列メソッドを使用していますか? – Novel

+1

@Novel私はそれらを忘れていたので。 :) – erip

+0

提案していただきありがとうございます。私は調査しようと...それは私にはすべて新しいです:) – Prijateljski

関連する問題