lal*_*lli 4 python listbox tkinter scrollbar
我正在使用列表框(带滚动条)进行日志记录:
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)
Run Code Online (Sandbox Code Playgroud)
现在,当我这样做时:
self.listbox_log.insert(END,str)
Run Code Online (Sandbox Code Playgroud)
我想要选择插入的元素.我试过了:
self.listbox_log.selection_anchor(END)
Run Code Online (Sandbox Code Playgroud)
但这不起作用......请建议一个解决方案......
vol*_*ing 10
据我所知滚动条控件不具有自动滚动功能,但它可以通过调用可以轻松实现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()
Run Code Online (Sandbox Code Playgroud)