[Tutor] Listbox selection

Michael Lange klappnase at freenet.de
Fri Aug 4 14:01:23 CEST 2006


Hi Joe,

On Thu, 3 Aug 2006 11:12:28 -0700
"Joe Cox" <jgcox39 at highstream.net> wrote:

> I am still having a problem getting my listbox's binded to the radiobuttons.
> I am getting closer.
> 
> ###Assign each Radiobutton with its own listbox values, show one selected
> button and one listbox###
> 
> 
> 
> from Tkinter import *
> 
> root = Tk()
> 
> var = StringVar()
> var.set('a')
> 
> { 'Aluminum' : ['Wrought', 'Die cast'],
>        'Steel'   : ['Low Carbon', 'Medium-high carbon','Alloy'] }
> 

Didn't you want to keep a reference to the dictionary?

> 
> def radio_command():
>     if var.get() == 'a':
>         # button with value 'a' selected
>         listbox.insert('a') #here I am trying to put the string starting
> with 'Steel' in the listbox
>     elif var.get() == 'b':
>         # button with value 'b' selected
>         listbox.insert('b')   #here I am trying to put the string starting
> with 'Aluminum' in the listbox
> 
> 
> 
> radio_a = Radiobutton(root,text="Steel", variable=var, value='a',
> command=radio_command).pack()

Are you aware that pack() returns None, so you actually assign None to all your
radio_* variables; if you want to keep access to the widgets you need to do:

    radio_a = Radiobutton()
    radio_a.pack()

> radio_b = Radiobutton(root,text="Aluminum", variable=var, value='b',
> command=radio_command).pack()
> radio_c = Radiobutton(root,text="Cast Iron", variable=var, value='c',
> command=radio_command).pack()
> radio_d = Radiobutton(root,text="Nickel", variable=var, value='d',
> command=radio_command).pack()
> radio_e = Radiobutton(root,text="Titaniuim", variable=var, value='e',
> command=radio_command).pack()
> 
> 
> listbox = Listbox(root)
> for item in ():
>     listbox.insert(END, item)

The last two lines don't really seem to have much sense, if you want an empty Listbox,
just don't insert anything.

> listbox.pack(side=LEFT, fill=BOTH)
> 
> root.mainloop()
> 


I am not sure what your question is here, maybe you want to try something like (untested):

    var = StringVar()
    var.set('Steel')
    listbox = Listbox(root)
    listbox.pack(side=LEFT, fill=BOTH)

    metals = {'Aluminum' : ['Wrought', 'Die cast'],
       'Steel'   : ['Low Carbon', 'Medium-high carbon','Alloy'] }

    def radio_command():
        listbox.delete(0, 'end')
        for m in metals[var.get()]:
            listbox.insert('end', m)

    for metal in metals.keys():
        # assuming that you don't need to keep references to all buttons
        Radiobutton(root, text=metal, variable=var, value=metal, command=radio_command).pack()

    # fill the listbox with initial values
    radio_command()

I hope this helps

Michael





More information about the Tutor mailing list