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

Joh*_*hnT 5 python tkinter python-3.x

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

我可以获得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()
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 7

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

您从中获得的元组yview表示顶部可见的分数和底部可见的分数。您可以致电yview_moveto设置顶部的位置,然后让 tkinter 处理底部的分数。

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