【发布时间】:2013-01-07 05:35:34
【问题描述】:
我发布了一个问题here,并建议我重组代码。现在已经不同了,我觉得有理由提出一个新问题。
无论如何,我正在尝试将拖放功能添加到列表框,但我认为最好的第一步是让事件绑定首先工作。目前,当我单击列表时,单击列表框时出现以下错误。出现列表框窗口,但是当我单击它时会发生错误。
"AttributeError: make_list instance has no attribute 'nearest'.
此外,当我在 build_listbox 方法中打印列表框时,会打印以下小数点 .40720520L。这不应该打印列表框中的值吗?毕竟,方法相同。列表框是否未正确创建?
from Tkinter import *
import Tkinter
class make_list:
def move_mouse(self, event):
self.curIndex = event.nearest(event.y)
print self.curIndex
def click_button(self, event):
w= event.widget
self.curIndex = int(w.curselection()[0])
#print self.curIndex
value = w.get(self.curIndex)
print value
def build_main_window(self):
self.build_listbox()
def build_listbox(self):
listbox = Listbox()
listbox.bind('<<ListboxSelect>>', self.click_button)
listbox.bind('<B1-Motion>', self.move_mouse)
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
listbox.insert(END, "a list entry")
listbox.pack()
print listbox
return
if __name__ == '__main__':
start = make_list()
start.build_main_window()
mainloop()
【问题讨论】:
-
您能否发布完整的回溯,以便我们知道是哪一行产生了异常?
-
实际上你在
move_mouse()定义的第一行得到了一个AttributeError: Event instance has no attribute 'nearest'。那是因为event对象没有nearest方法函数属性。 -
顺便说一句,PEP 8 的类命名约定是
CapCase所以make_list应该是MakeList。 -
ListBox对象有一个curselection()方法,它返回您应该使用的所选元素的行号。我建议您花一些时间阅读网络上和各种书籍中存在的众多Tkintertutorials 之一。 -
对不起,我的错误。
listvariable是小部件选项而不是属性,因此检索其当前值是使用listbox.cget('listvariable')完成的——但是,由于未知原因,它返回一个空字符串。起作用的是listbox.get(0, END),它返回元组('one', 'two', 'three', 'four', 'a list entry')。顺便说一句,在build_listbox()中创建的ListBox实例存储在局部变量listbox中,并且会在函数返回时自动删除——所以我建议您改为(或也)将值分配给self.listbox以防止这不会发生。
标签: python events listbox widget tkinter