TkListbox -- binding an entry

Hello,

I’ve spent the last few hours trying to figure this out.

I have a TkListbox, and I’d like to take an action when the user clicks on
a list entry. There are two ways that this might be possible:

  • Bind each entry to a callback.
  • Bind the list box to a callback and then find the entry that is
    highlighted.

If anyone knows how to do either of these two things, I would really like
to know. I can bind the list box, but I haven’t managed to get any useful
information from the event widget. I have no idea how I can bind a
particular entry.

If anyone knows where I can find good documentation, I would really
appreciate it. All I’ve found is a short tutorial, which doesn’t answer
my particular question.

Thanks for the help.

···


Daniel Carrera
Graduate Teaching Assistant. Math Dept.
University of Maryland. (301) 405-5137

Hi,

···

From: Daniel Carrera dcarrera@math.umd.edu
Subject: TkListbox – binding an entry
Date: Fri, 31 Jan 2003 07:46:33 +0900
Message-ID: 20030130224627.GA2517@math.umd.edu

I have a TkListbox, and I’d like to take an action when the user clicks on
a list entry. There are two ways that this might be possible:

  • Bind each entry to a callback.
  • Bind the list box to a callback and then find the entry that is
    highlighted.

I recommend you to use TkListbox#nearest method and
binding to listbox widget. A sample script is here.

#!/usr/bin/env ruby
require ‘tk’

f = TkFrame.new.pack

lbox = TkListbox.new(f,‘selectmode’=>‘multiple’).pack(‘side’=>‘left’)

[‘aaa’, ‘bbb’, ‘ccc’, ‘ddd’, ‘eee’, ‘fff’, ‘ggg’,
‘hhh’, ‘iii’, ‘jjj’, ‘kkk’, ‘lll’, ‘mmm’, ‘nnn’].each{|term|
lbox.insert ‘end’,term
}

lbox.yscrollbar(TkScrollbar.new(f).pack(‘side’=>‘left’, ‘fill’=>‘y’))

tag = TkBindTag.new
lbox.bindtags(lbox.bindtags.unshift(tag))
tag.bind(‘Button-1’,
proc{|w,y|
p w.get(w.nearest(y))
Tk.callback_break # block original binding of listbox widget
}, ‘%W %y’)

Tk.mainloop


Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)