Tkinter - 自动滚动到底部 [英] Tkinter - autoscroll to bottom
问题描述
我有一张画布.画布内部是一个框架.在那个框架里面是一个标签.随着标签中文本的增长,画布的大小也随之增长以适应.我设置了一个垂直滚动条,它允许我看到超出窗口大小的文本.滚动条按预期工作,但我希望它随着文本的增长自动滚动到底部(即保持锁定到底部).我该怎么做?
I have a canvas. Inside the canvas is a frame. And inside that frame is a label. As the text in the label grows, the canvas grows in size to accommodate. I've setup a vertical scrollbar, that allows me to see the text that overflows the window size. The scrollbar works as expected, but I want it to automatically scroll to the bottom (i.e. stay locked to the bottom) as the text grows. How can I do this?
使用 canvas.yview_moveto( 1 )
什么都不做...
Using canvas.yview_moveto( 1 )
does nothing...
下面是我的代码:
def tk_onFrameConfigure( self, event ):
# resize canvas
self.tkCanvas.configure( scrollregion = self.tkCanvas.bbox( 'all' ) )
def tk_onCanvasConfigure( self, event ):
# resize frame
self.tkCanvas.itemconfigure( self.tkCanvasFrame, width = event.width )
def setupTkinter( self ):
self.tkRoot = tkinter.Tk()
self.tkCanvas = tkinter.Canvas( self.tkRoot )
self.tkCanvas.pack( side = tkinter.LEFT, expand = True, fill = 'both' )
self.tkCanvas.configure(
width = self.width,
height = self.height,
highlightthickness = 0,
bg = self.bgColor
)
scrollbar = tkinter.Scrollbar( self.tkRoot )
scrollbar.pack( side = tkinter.RIGHT, fill = 'y' )
scrollbar.configure(
orient = 'vertical',
command = self.tkCanvas.yview
)
self.tkCanvas.configure( yscrollcommand = scrollbar.set )
# self.tkCanvas.yview_moveto( 1 ) # does nothing
frame = tkinter.Frame( self.tkCanvas )
self.tkCanvasFrame = self.tkCanvas.create_window(
( 0, 0 ),
window = frame,
anchor = 'nw'
)
self.tkTextBox = tkinter.Label( frame )
self.tkTextBox.pack( expand = True, fill = 'both' )
self.tkTextBox[ 'text' ] = self.displayBuffer
self.tkTextBox.config(
fg = self.textColor,
bg = self.bgColor,
anchor = 'nw',
justify = tkinter.LEFT,
wraplength = self.width - 5
)
frame.bind( '<Configure>', self.tk_onFrameConfigure )
self.tkCanvas.bind( '<Configure>', self.tk_onCanvasConfigure )
self.tkRoot.mainloop()
推荐答案
我在此处找到了解决方案.canvas.yview_moveto( 1 )
似乎什么都不做,因为我在设置过程中只调用了一次.为了使自动"滚动起作用,每次文本增长时我都需要调用它.
I found the solution here. canvas.yview_moveto( 1 )
appears to do nothing because I only call it once during setup. For the 'auto' scrolling to work, I need to call it each time the text grows.
这篇关于Tkinter - 自动滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!