如何在Tkinter Listbox插入时添加自动滚动?
我正在使用一个带滚动条的列表框来记录信息:
self.listbox_log = Tkinter.Listbox(root, height = 5, width = 0,)
self.scrollbar_log = Tkinter.Scrollbar(root,)
self.listbox_log.configure(yscrollcommand = self.scrollbar_log.set)
self.scrollbar_log.configure(command = self.listbox_log.yview)
现在,当我执行:
self.listbox_log.insert(END,str)
我希望插入的元素能够被选中。我试过:
self.listbox_log.selection_anchor(END)
但是那样不行……请给我一些建议……
2 个回答
2
试着这样做。(我从另一个问题复制过来的:如何让gtk.scrolledwindow自动滚动?)对我来说效果很好。
def on_TextOfLog_size_allocate(self, widget, event, data=None):
adj = self.scrolled_window.get_vadjustment()
adj.set_value( adj.upper - adj.page_size )
17
据我所知,ScrollBar这个小部件没有自动滚动的功能,不过我们可以很简单地实现这个功能。只需要在插入新项目后,调用一下listBox
的yview()
方法就可以了。如果你想让新插入的项目被选中,也可以手动使用listbox
的select_set
方法来做到这一点。
from Tkinter import *
class AutoScrollListBox_demo:
def __init__(self, master):
frame = Frame(master, width=500, height=400, bd=1)
frame.pack()
self.listbox_log = Listbox(frame, height=4)
self.scrollbar_log = Scrollbar(frame)
self.scrollbar_log.pack(side=RIGHT, fill=Y)
self.listbox_log.pack(side=LEFT,fill=Y)
self.listbox_log.configure(yscrollcommand = self.scrollbar_log.set)
self.scrollbar_log.configure(command = self.listbox_log.yview)
b = Button(text="Add", command=self.onAdd)
b.pack()
#Just to show unique items in the list
self.item_num = 0
def onAdd(self):
self.listbox_log.insert(END, "test %s" %(str(self.item_num))) #Insert a new item at the end of the list
self.listbox_log.select_clear(self.listbox_log.size() - 2) #Clear the current selected item
self.listbox_log.select_set(END) #Select the new item
self.listbox_log.yview(END) #Set the scrollbar to the end of the listbox
self.item_num += 1
root = Tk()
all = AutoScrollListBox_demo(root)
root.title('AutoScroll ListBox Demo')
root.mainloop()