更改内容时,阻止“文本"小部件滚动 [英] Stop Text widget from scrolling when content is changed
问题描述
我有一个带有滚动条的文本小部件,看起来像这样:
I have a text widget with a scrollbar which looks something like this:
self.myWidget = Text(root)
self.myWidget.configure(state=DISABLED)
self.myWidget.pack()
self.myWidgetScrollbar = Scrollbar(root, command=self.myWidget.yview)
self.myWidget.configure(yscrollcommand=self.myWidgetScrollbar.set)
self.myWidgetScrollbar.pack(side=LEFT,fill=Y)
文本小部件每秒更新4次,如下:
The text widget is updated 4 times per second with:
self.myWidget.configure(state=NORMAL)
self.myWidget.delete(1.0, END)
self.myWidget.insert(END, "\n".join(self.listWithStuff))
self.myWidget.configure(state=DISABLED)
问题在于,当我尝试滚动时,它会一直将我滚动回到顶部(可能每秒滚动4次).我认为这是因为所有内容都已删除.
The problem is that when I try to scroll, it keeps scrolling me back up to the top (4 times per second, probably). I assume this is because all content is removed.
如何防止它自动滚动,或者在内容更改后可能会向后滚动?
How can I prevent it from scrolling automatically, or possibly scroll "back" when the content has changed?
推荐答案
您可以保护位置并在更新后将其重新设置,例如Tcl代码:
You can safe the position and set it back after an update, like this Tcl code does:
proc update_view {w s data} {
# store position
set pos [$s get]
$w configure -state normal -yscrollcommand {}
$w delete 1.0 end
$w insert end $data
$w configure -state disabled -yscrollcommand [list $s set]
$s get
$s set {*}$pos
}
Tkinter代码看起来类似,类似于:
The Tkinter code would look similar, something like:
def update_view(self, data):
pos = self.myWidgetScrollbar.get()
self.myWidget.configure(yscrollcommand=None, state=NORMAL)
self.myWidget.delete(1.0, END)
self.myWidget.insert(END, data)
self.myWidget.configure(yscrollcommand=self.myWidgetScrollbar.set, state=DISABLED)
self.myWidgetScrollbar.get()
self.myWidgetScrollbar.set(pos)
不确定为什么需要介于两者之间的get(),也许可以强制进行一些查找,但是仍然可以.
Not sure why the get() in between is needed, maybe to force some lookup, but it works.
这篇关于更改内容时,阻止“文本"小部件滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!