首页 > 解决方案 > 如何永远保存字典的键?

问题描述

我正在尝试使用 python 和 tkinter 制作电话簿。我需要通过向字典添加元素来向我的电话簿添加新号码,但在程序关闭后我无法再次访问这些号码。

from tkinter import*
#defining the submit button
def submit():
  global my_dict
  new = entry2.get()
  new2 = entry3.get()
  my_dict.update({new:new2})


 #definig the add button
 def add():
    top = Toplevel(root)
    top.configure(background="black")
    top.geometry("400x400")
    top.title("Add new member")
    label6 =Label(top,text="Welcome",bg="black",fg="orange")
    label6.place(x=135,y=13)
    global entry2
    entry2 = Entry(top,width=23)
    entry2.place(x=102,y=78)
    label7 = Label(top,text="Name",bg="black",fg="orange")
    label7.place(x=48,y=78)
    global entry3
    entry3 = Entry(top,width = 23)
    entry3.place(x=108,y=127)
    label8 = Label(top,text="phone number",bg ="black",fg="orange")
    label8.place(x=0,y=129)
    button3 = Button(top,text="Submit",command = submit)
    button3.place(x=185,y=200)
    button5 = Button(top,text = "close",command = top.quit)
    button5.place(x=185,y=300)
  #defining the chek button
 def check():
     person = entry.get()
        if person in my_dict:
        phone = my_dict.get(person)
        print("Found: " + person + " : " + phone)
       # Erase the old result by placing a blank label
       label0 = Label(root, width=200, bg ="black", fg = "black").place(x=10,y=167)
       label5 = Label(root, text = person + " : " + phone, bg ="black", fg =    "orange").place(x=10,y=167)

 #creating the main window  
 root = Tk()
 global my_dict
  my_dict = {"john":'7598769587'}
  root.title("vole phone book")
 root.geometry("400x400")
 root.configure(background="black")
 label = Label(root,text="phone book",bg="black",fg="orange",width=13).place(x=133,y=23)
 label2 = Label(root,text="Enter here.",bg = "black",fg="orange").place(x=2,y=89)
 entry = Entry(root,width = 27)
 entry.place(x=89,y=90)
 button =Button(root,text="Check",bg="yellow",fg="red",command=check).place(x=190,y=129)
 button2=Button(root,text="Add",width=23,command = add).place(x=120,y=300)

 root.mainloop()

这是我的代码,怎么办?

标签: pythontkinter

解决方案


Python 中的变量不会保存到磁盘,它们只存在于内存 (RAM) 中,除非您自己显式地将其保存在那里。您可以直接保存到文件,也可以改用数据库。

请参阅此处了解如何使用 Pickle 来做您想做的事情。


推荐阅读