关闭时是否可以让 Tkinter 记住变量 [英] Is it possible to make Tkinter remember variables when you close it

查看:23
本文介绍了关闭时是否可以让 Tkinter 记住变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我打开程序时,我想拥有我离开时相同的设置.例如,将标签设置为一个值,当我关闭程序并再次打开它时仍然是该值.这在 Tkinter 中可能吗?如果是这样,我会怎么做?

When i open the program, I want to have the same settings there were when i left. For instance setting a label to a value and still be that value when i close the program and open it again. Is this possible in Tkinter? If so, how would i do it?

推荐答案

将数据存储到某处(文本文件、jsonpickle 或其他东西)并加载它在启动期间.

Store the data to somewhere (a text file, json, pickle or something else) and load it during startup.

所以你的程序可能是这样的:

So your program may look like this:

from tkinter import *
import os

tk=Tk()
var=StringVar()
Entry(tk,textvariable=var).pack()

# load the text before startup
if os.path.isfile('save.txt'):
    with open('save.txt','r') as f:
        var.set(f.read())

mainloop()

# save the text after shutdown
with open('save.txt','w') as f:
    f.write(var.get())

这篇关于关闭时是否可以让 Tkinter 记住变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆