在python tkinter中设置滚动条位置的正确方法

时间:2018-11-05 15:58:04

标签: python python-3.x tkinter

我正在制作一个基本的文本编辑器,并且在关闭程序时将滚动位置保存在一个文件中。然后,在打开程序时,它将从文件中读取滚动位置并进行更新,因此您可以从上次停止的地方继续。

我可以从scrolledtext.yview()得到好的位置,该位置返回一个元组,例如(0.42,0.75)

但是我不知道如何更改滚动位置。我已经尝试过scrolledtext.vbar.set(0.42, 0.75)来尝试对其进行更新,但是它不起作用,因为它不执行任何操作,也没有给出错误。我也尝试过scrolledtext.yview(0.42, 0.75),但是它说TclError: bad option "0.42": must be moveto or scroll,所以如果有人知道如何更新它,将不胜感激,欢呼。

编辑(代码):

import tkinter as tk

root = tk.Tk()
Frame = frame(root)
Frame.pack()
textbox = ScrolledText(Frame)
textbox.pack()
textbox.yview()  #this is saved to file, produces tuple of e.g. (0.42, 0.75)
textbox.vbar.set(0.3, 0.7)  #this doesn't produce any errors but doesn't change the scroll position 
textbox.yview(0.3, 0.7)  #this is also something i have tried but produces the error _tkinter.TclError: bad option "0.4243827160493827": must be moveto or scroll

root.mainloop()

2 个答案:

答案 0 :(得分:1)

您不能指望保存的yview在所有情况下都能正常工作。如果文件已被编辑,则比例可能全部错误。

yview获得的元组表示在顶部可见的分数和在底部可见的分数。您可以调用yview_moveto将位置设置在顶部,然后让tkinter照顾底部的分数。

例如,如果您保存的yview是(0.42, 0.75),则只需要调用yview_moveto('0.42')。这将导致视图被调整,以使给定的偏移量位于窗口的顶部。

答案 1 :(得分:0)

如果小部件随着 bbox 大小的变化而更新,我使用以下代码段来保持滚动位置:

div
相关问题