我有麻煩的事件結合使用Python/Tkinter的工作。我只是試圖點擊並打印位置,但每次我這樣做時,結果都是「-1」。蟒蛇Tkinter的列表框的事件綁定
這裏是我的代碼
from Tkinter import *
import Tkinter
class make_list(Tkinter.Listbox):
def __init__(self,master, **kw):
frame = Frame(master)
frame.pack()
self.build_main_window(frame)
kw['selectmode'] = Tkinter.SINGLE
Tkinter.Listbox.__init__(self, master, kw)
master.bind('<Button-1>', self.click_button)
master.curIndex = None
#display the clicked location
def click_button(self, event):
self.curIndex = self.nearest(event.x)
print self.curIndex
#display the window, calls the listbox
def build_main_window(self, frame):
self.build_listbox(frame)
#listbox
def build_listbox(self, frame):
listbox = Listbox(frame)
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
listbox.insert(END, "a list entry")
listbox.pack()
return
if __name__ == '__main__':
tk = Tkinter.Tk()
make_list(tk)
tk.mainloop()
更新的代碼 - 我擺脫了框架,但我似乎無法找出爲什麼我在功能click_button越來越-1第一個print語句
from Tkinter import *
import Tkinter
class make_list(Tkinter.Listbox):
#display the clicked location
def click_button(self, event):
##this block works
w = event.widget
index = int(w.curselection()[0])
value = w.get(index)
print value
##this doesn't
self.curIndex = self.nearest(event.y)
print self.curIndex
self.curIndex = event.widget.nearest(event.y)
print self.curIndex
#display the window, calls the listbox
def build_main_window(self):
self.build_listbox()
#listbox
def build_listbox(self):
listbox = Listbox()
listbox.bind('<<ListboxSelect>>', self.click_button)
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
listbox.insert(END, "a list entry")
listbox.pack()
return
if __name__ == '__main__':
tk = Tkinter.Tk()
start = make_list(tk)
start.build_main_window()
start.mainloop()
你所說的打印「位置」是什麼意思?你想要項目的索引,x/y座標還是當前選中的數據? –