2017-10-26 3 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

관련 문제