如何保存数据,使其在关闭并重新打开tkinter应用程序后仍然存在?

2024-04-18 22:31:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个简单的应用程序,您可以在其中输入一个单词,然后按按钮,每次按按钮,屏幕上会显示一个图像和两个标签,其中一个标签包含您键入的单词。我想这样做,如果你关闭应用程序并重新打开它,你按下按钮放置的图像和标签仍然存在。这怎么可能呢

from tkinter import *
import pickle
import calendar
from tkcalendar import *

import calendar

from tkcalendar import *
from datetime import datetime
from datetime import date
from time import strftime
from datetime import timedelta, datetime, date
from ttkthemes import ThemedTk, THEMES
import pickle

self = Tk()
self.title('Storing data')
self.geometry("850x800")

x = 200
y = 250
c = 460
d = 290
e = 325
f = 355
g = 390
h = 420
i = 460
j = 490

LARGE_FONT= ("Verdana", 24)
SMALL_FONT=("Verdana", 12)


def get_text(file):
    with open(file, "r") as MyFile:
        return MyFile.read()


def edit_text(file, text, img_dir):
    with open(file, "w") as MyFile:
        MyFile.write(text + "\n" + "apple.png")


def step(self):
    my_progress['value']+= 5
        

def display():

    global x , y , c , d , e , f , g, h, i, j
    box_image = PhotoImage(file='apple.png')
    panel2 = Label(self, image=box_image, bg='#f7f6f6')
    panel2.image = box_image
    panel2.place(x=x, y=y)
    x=x
    y = y+260
    #assessment name
    n = Label(self, text="", bg="#e0f6fc", font=60)
    
    n.configure(text=assessment_name.get())
    n.pack()
    
    #due date
    d = Label(self, text="Due:", bg="#e0f6fc", font=SMALL_FONT)
    d.pack()
    #cal date
    c= Label(self, text="", bg="#e0f6fc", font=SMALL_FONT)
    c.pack()
        
    
button = Button(self, text="place", command=display)
button.pack()

save = Button(self, text="save", command=edit_text)
save.pack()

open_button =Button(self, text="open", command=get_text)
open_button.pack()


edit_text("textfile.txt", "label contents", "apple.png")



  

assessment_name = Entry(self)
assessment_name.place(relx=0.5, y=220, anchor='center')

global cal2
cal2 = Calendar(self, background="#e0f6fc", disabledbackground="white", bordercolor="light blue", headersbackground="light blue", normalbackground="#e0f6fc", foreground="black", normalforeground='black', headersforeground='white', selectmode="day", year=2021, month=8, day=9)
cal2.place(relx=0.5, y=400, anchor='center')

due_date = Button(self, text="Submit")
due_date.place(relx=0.5, y=510, anchor='center')







self.mainloop()

Tags: textfromimageimportselfdatetimedatedef
3条回答

如果要保存某些内容供以后使用,可以将其保存到文本文件中。您可以保存图像的文本和目录

首先,在需要的地方创建一个.txt文件(与代码最好在同一文件夹中)。 接下来,创建一个从文件中获取文本的函数:

def get_text(file):
    with open(file, "r") as MyFile:
        return MyFile.read()

此代码将返回一个字符串,其中包含文本文件中的内容。 接下来,创建一个可以编辑文件的函数。最好将其删除并重新写入

def edit_text(file, text, img_dir):
    with open(file "w") as MyFile:
        MyFile.write(text + "\n" + img_dir)

调用此函数时,它会将文件内容更改为输入的内容。例如:

edit_text("textfile.txt", "label contents", "apple.png")

这会将“textfile.txt”的内容更改为:

label contents
apple.png

您可以使用它来存储应用程序的数据。我希望这有帮助

以下是更详细的解释:

要实现这一点,您需要将保存的数据存储在外部文件中。这需要了解^{}^{}^{}^{}函数

首先,我们将创建要存储数据的json文件,例如:myJson.json

在该文件中,使用要存储的值创建一个字典,例如:{"entryVal": "Hello World!"}

以下是我们将构建的基本GUI:

from tkinter import *
import json

root = Tk()

toSave = StringVar()
Entry(root, textvariable = toSave) .pack()

Button(root, text = "save value!") .pack()

root.mainloop()

接下来,我们需要定义两个函数:一个用于打开Json,另一个用于保存Json

def openJson():
    with open('myJson.json', 'r') as f:
        value = json.loads(f.read())["entryVal"]
        toSave.set(value)

def saveJson():
    with open('myJson.json', 'w') as f:
        currentVal = json.dumps({"entryVal":toSave.get()})
        f.write(currentVal)

openJson()将打开Json文件,从Json解码,获取“entryVal”的键值,并将我们的输入框设置为包含找到的文本

saveJson()将从我们的条目中获取值,将其放在“entryVal”键下的字典中,编码为Json,然后将其写入保存文件

现在我们只需要在启动程序时调用openJson(),并创建一个按钮来触发saveJson():

from tkinter import *
import json

root = Tk()

def openJson():
    with open('myJson.json', 'r') as f:
        value = json.loads(f.read())["entryVal"]
        toSave.set(value)

def saveJson():
    with open('myJson.json', 'w') as f:
        currentVal = json.dumps({"entryVal":toSave.get()})
        f.write(currentVal)

toSave = StringVar()
Entry(root, textvariable = toSave) .pack()

Button(root, text = "save value!", command = saveJson) .pack()

openJson()

root.mainloop()

虽然可以将数据保存到txt中,但在我看来,将其存储为JSON要容易得多。使用JSON,您可以存储一个值字典,并快速轻松地调用它们。然后,您可以将这些值设置为应用程序中的各种参数

Python还有一个内置的JSON库,所以您所要做的就是import json。您可以找到文档here

相关问题 更多 >