将事件和边框宽度绑定到列表框条目



我曾想过将事件绑定到Listbox条目(Listbox的成员(,但我已经在文档中进行了搜索。没有。但它似乎是可能的,因为它对鼠标点击做出反应。有什么方法可以将事件添加到列表框条目中吗?

我试图为列表框中的每个项目添加边框宽度,但它显示

_tkinter.TclError: unknown option "-bd"

我想知道为列表框的成员添加边框宽度的可能方法。此代码将bg添加到列表框条目中,即使对fg有效,但对bd失败

from tkinter import *
root=Tk()
class Test(Listbox):
def __init__(self,p):
super().__init__(p)
self.insert(END,'a') 
self.itemconfig(END,{'bg':'blue','bd':6})
self.insert(END,'b') 
self.itemconfig(END,{'bg':'orange'})
self.insert(END,'c') 
self.itemconfig(END,{'bg':'red'})
self.insert(END,'d') 
self.itemconfig(END,{'bg':'green'})
a=Test(root)
a.pack()
root.mainloop()

编辑:

对于绑定事件,我指的是<输入>并且<离开>

我之前的评论说错了,对此我深表歉意。不能为单个项目指定边框宽度。itemconfigure只接受backgroundforegroundselectbackgroundselectforeground

至于";添加";事件-不能添加事件。您可以绑定到所有标准事件,这是有文档记录的,与任何其他小部件一样工作。此外,您可以绑定到<<ListboxSelect>>,以便在选择发生更改时调用函数。

根据Bryan的评论,我知道我们不能对Listbox元素使用bd/bind事件,所以我决定使用一个Listbox集合,其中每个Listbox都有一个bd和一个绑定到它的事件。

在这篇文章中,我使用了canvas+滚动条来包含这些列表框。单击某个元素以复制其文本,并将鼠标悬停在上面以获得一些效果。

from tkinter import *
class LogBox(Canvas):
def __init__(self,p):
super().__init__(p)
self.MFrame=Frame(self)
self.Vbar=Scrollbar(p,orient=VERTICAL,command=self.yview)
self.bind('<Configure>',lambda e:self.configure(scrollregion=self.bbox('all')))
self.bind_all('<MouseWheel>',self.orientScreen)
self.create_window((0,0),window=self.MFrame,anchor='nw',width=1350)
self.VFrame=Frame(self.MFrame)
self.VFrame.pack(fill=X)
self.config(yscrollcommand=self.Vbar.set)
self.config(relief=FLAT)
self.Vbar.pack(side=RIGHT,fill=Y)
def append(self,text,color):
lst=Listbox(self.VFrame,borderwidth=3,height=1,relief=FLAT,font=('helvetica',12,'bold')) # border width thing
lst.bind('<Enter>',lambda X:self.hover(lst,True)) # for hover effects
lst.bind('<Leave>',lambda X:self.hover(lst,False))
lst.insert(END,text)
lst.config(bg='orange')
lst.itemconfig(END,{'bg':color})
lst.pack(fill=X)        
lst.bind('<<ListboxSelect>>',lambda x:self.copy_button(text)) # for click event
def orientScreen(self,event):
self.yview_scroll(int(-1*(event.delta/120)),'units')
def hover(self,lst,status):
if status:
lst.config(bg='red',font=('helvetica',15,'bold'))            
else:
lst.config(bg='orange',font=('helvetica',12,'bold'))            
def copy_button(self,text):        
d = Tk()
d.withdraw()
d.clipboard_clear()
d.clipboard_append(text)
d.destroy()
if __name__=='__main__':
root=Tk()
f=Frame(root)
b=LogBox(f)
for i in range(1000):
b.append(i,'orange')
b.pack()
f.pack()
root.mainloop()

最新更新