You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何保存tkinter应用数据 实现关闭重启后添加的图片标签仍存在

实现方案

要实现关闭应用重启后保留之前添加的图片和Label,核心逻辑是把每次新增的条目元数据持久化存储到本地文件,程序启动时读取存储的数据重新渲染对应控件,具体修改后的可运行代码如下:

from tkinter import *
import pickle
from tkcalendar import *
from datetime import datetime

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

# 坐标初始值
x = 200
y = 250

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

# 存储所有条目数据,存字典:{输入内容, 截止日期, 图片路径}
entry_data = []
# 存储图片引用,防止被垃圾回收导致图片不显示
image_refs = []
# 存储文件路径
SAVE_FILE = "entry_data.pkl"

def save_data():
    """保存所有条目数据到本地"""
    with open(SAVE_FILE, "wb") as f:
        pickle.dump(entry_data, f)

def load_data():
    """启动时加载本地存储的条目数据"""
    global entry_data, y
    try:
        with open(SAVE_FILE, "rb") as f:
            entry_data = pickle.load(f)
        # 恢复y坐标的位置
        y = 250 + 260 * len(entry_data)
        # 遍历数据重建控件
        for item in entry_data:
            render_item(item)
    except FileNotFoundError:
        # 第一次运行没有存储文件,直接返回
        entry_data = []

def render_item(item):
    """根据条目数据渲染图片和Label"""
    global x, y
    # 渲染图片
    box_image = PhotoImage(file=item['img_path'])
    image_refs.append(box_image)
    panel2 = Label(root, image=box_image, bg='#f7f6f6')
    panel2.image = box_image
    panel2.place(x=x, y=y)
    y += 260
    # 渲染输入内容Label
    n = Label(root, text=item['input_text'], bg="#e0f6fc", font=60)
    n.pack()
    # 渲染截止日期Label
    d = Label(root, text="Due:", bg="#e0f6fc", font=SMALL_FONT)
    d.pack()
    c = Label(root, text=item['due_date'], bg="#e0f6fc", font=SMALL_FONT)
    c.pack()

def display():
    """点击place按钮的触发逻辑"""
    # 获取当前输入和选中的日期
    current_input = assessment_name.get()
    current_due_date = cal2.get_date()
    # 构造条目字典
    item = {
        "input_text": current_input,
        "due_date": current_due_date,
        "img_path": "apple.png"
    }
    # 加到存储列表
    entry_data.append(item)
    # 渲染到界面
    render_item(item)
    # 保存到本地
    save_data()
    # 清空输入框
    assessment_name.delete(0, END)

# 按钮定义
button = Button(root, text="place", command=display)
button.pack()

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

cal2 = Calendar(root, 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(root, text="Submit")
due_date.place(relx=0.5, y=510, anchor='center')

# 启动时先加载之前存储的条目
load_data()

root.mainloop()

功能说明

  • 每次点击place按钮,会自动把当前输入的内容、选中的日历日期和图片路径存储到本地entry_data.pkl文件
  • 程序每次启动时会自动读取该文件,重建之前添加的所有图片和Label控件
  • 无需额外点击保存/打开按钮,操作和原来一致

内容的提问来源于stack exchange,提问作者Minbutt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:15:06