Python 如何在Tkinter列表框中插入时添加自动滚动?

Python 如何在Tkinter列表框中插入时添加自动滚动?,python,listbox,scrollbar,tkinter,Python,Listbox,Scrollbar,Tkinter,我正在使用一个列表框(带滚动条)进行日志记录: 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.li

我正在使用一个列表框(带滚动条)进行日志记录:

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)

但这不起作用。。。请建议一个解决方案…

如果ScrollBar小部件没有自动滚动功能,但是在插入新项目后,可以通过调用
列表框的
yview()
方法轻松实现。如果需要选择新项目,也可以使用
列表框
选择集
方法手动进行选择

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()
试着这样做。(我抄袭了另一个问题:如何自动滚动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 )

您也可以使用listbox“see”命令,尽管在查看end元素时效果相同。谢谢,我使用了self.listbox\u log.insert(end,str)size=len(self.listbox\u log.get(-1,end))self.listbox\u log.yview\u scroll(size,“units”)您的方式更加优雅。这在列表框上不起作用,因为没有
get\u vaadjustment
方法,原始问题也没有提到任何有关名为
滚动窗口的小部件的内容。你确定你把这个答案贴到了正确的问题上吗?我用的是pygtk而不是tkint,很抱歉弄错了。