[Tutor] problems using a listbox

Peter Otten __peter__ at web.de
Tue Oct 17 05:13:42 EDT 2017


Chris Roy-Smith wrote:

> OS: Linux Chris-X451MA 4.4.0-97-generic #120-Ubuntu SMP Tue Sep 19 
> 17:28:18 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
> 
> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
> 
> I am trying to learn how to use a tkinter listbox. When I execute my 
> experimental code, an odd index is printed immediately (output below 
> code), index looks wrong (shouldn’t it be an integer). Also it doesn't 
> print new values when I select an entry.
> 
> ---------------------------------------------------
> 
> #!/usr/bin/python3
> #test listbox
> from tkinter import *
> 
> class Dialog(Frame):
> 
>      def __init__(self, master):
>          Frame.__init__(self, master)
>          self.list = Listbox(self, selectmode=EXTENDED)
>          self.list.pack(fill=BOTH, expand=1)
>          self.current = None
>          self.poll() # start polling the list
> 
>      def poll(self):
>          now = self.list.curselection()
>          if now != self.current:
>              self.list_has_changed(now)
>              self.current = now
>          self.after(250, self.poll)
> 
>      def list_has_changed(self, selection):
>          print ("selection is", selection)
> 
> 
> snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry')
> master = Tk()
> 
> listbox = Listbox(master)
> listbox.grid(row=0)
> 
> for item in snames:
>      listbox.insert(END, item)

The problem is your inconsistent use of the Dialog class which you do not 
instantiate.
 
> myindicator=Dialog.list_has_changed(master, listbox)

Here you call list_has_changed() like a function. The first argument (self) 
is your `master` object, the second is the listbox. In a nutshell you are 
doing

>>> from tkinter import *
>>> master = Tk()
>>> listbox = Listbox(master)
>>> print(listbox)
.140206885684560

and what is displayed when you are printing a tkinter widget is its Tcl/Tk 
name -- which admittedly looks odd.
 
> mainloop()

A fix with minimal changes might be

#!/usr/bin/python3
#test listbox
from tkinter import *

class Dialog(Frame):

     def __init__(self, master):
         Frame.__init__(self, master)
         self.list = Listbox(self, selectmode=EXTENDED)
         self.list.pack(fill=BOTH, expand=1)
         self.current = None
         self.poll() # start polling the list

     def poll(self):
         now = self.list.curselection()
         if now != self.current:
             self.list_has_changed(now)
             self.current = now
         self.after(250, self.poll)

     def list_has_changed(self, selection):
         print ("selection is", selection)


snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry')
master = Tk()

dialog = Dialog(master)
dialog.pack()

for item in snames:
     dialog.list.insert(END, item)

mainloop()




More information about the Tutor mailing list