需要帮助让程序记住设置,cPickle
如何让此代码在重新打开时记住秤的最后位置?
import Tkinter
import cPickle
root = Tkinter.Tk()
root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1)
root.sclX.pack(ipadx=75)
root.resizable(False,False)
root.title('Scale')
with open('myconfig.pk', 'wb') as f:
cPickle.dump(root.config(), f, -1);
cPickle.dump(root.sclX.config(), f, -1);
root.mainloop()
How do I make this code remember the last position of the scale, upon reopening?
import Tkinter
import cPickle
root = Tkinter.Tk()
root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1)
root.sclX.pack(ipadx=75)
root.resizable(False,False)
root.title('Scale')
with open('myconfig.pk', 'wb') as f:
cPickle.dump(root.config(), f, -1);
cPickle.dump(root.sclX.config(), f, -1);
root.mainloop()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要进行许多更改和修复才能使代码按预期工作:
让我们从顶部看一下更改。我引入了一个 Tkinter 变量
root.place
,以便可以在全局变量place 中随时跟踪刻度的位置(通过后面的函数
(使用 OOP 并避免全局变量会更优雅,但我试图让事情变得简单;-)。tracer
)然后,如果
.pk
文件可读,则 try/ except/else 语句会更改place
的设置。你从来没有试图读回你保存的内容。最后但并非最不重要的一点是,我将保存操作移至主循环退出后,并简化了它(您不需要所有的配置字典——无论如何您都无法访问它们——只需
地点
全球)。您在主循环启动之前保存,因此“保存”初始值(不是由主循环执行更改的值)。tracer
函数和.trace
方法调用确保全局变量place
始终记录秤的最新位置 - 以便可以恢复它,并且在主循环退出后保存(主循环退出后,所有 Tkinter 对象,包括 GUI 对象和变量,都变得不可访问)。You need many changes and fixes to make your code work as intended:
Let's look at the changes from the top. I've introduced a Tkinter variable
root.place
so that the position of the scale can be tracked at all times (via later functiontracer
) in global variableplace
(it would be more elegant to use OOP and avoid global variables, but I'm trying to keep things simple for you;-).Then, the try/except/else statement changes the setting of
place
iff the.pk
file is readable. You were never trying to read back what you had saved.Last but not least, I've moved the save operation to after mainloop exits, and simplified it (you don't need all of the config dictionaries -- which you can't access at that point anyway -- just the
place
global). You were saving before mainloop started, therefore "saving" the initial values (not those changed by the main loop execution).The
tracer
function and.trace
method calls ensure that global variableplace
always records the scale's latest position -- so that it can be recovered, and saved, after mainloop has exited (after mainloop exits, all Tkinter objects, both GUI ones and variables, become inaccessible).