Event triggered by Listbox and Radiobutton in Tkinter

ferryard picture ferryard · Oct 13, 2014 · Viewed 7.3k times · Source

I want to make an event that is triggered by either a change in List box selected item or a change in Radio button selected item. Is it possible? I use this code:

def getScript(event):
    state = rb.get()
    listScript = []
    processor = ()
    processor = lb1.get(lb1.curselection())
    if processor :
        if (state == 1):
            print processor
        if (state == 2):
            pass
        if (state == 3):
            pass


frame2 = Frame(top)
frame2.pack(fill = X)
rb = IntVar()

R1 = Radiobutton(frame2, text = "Parallel Test", 
                 variable = rb, value = 1, command = getScript)
R2 = Radiobutton(frame2, text = "Non Parallel Test", 
                 variable = rb, value = 2, command = getScript)
R3 = Radiobutton(frame2, text = "Specific Test", 
                 variable = rb, value = 3, command = getScript)

R1.grid(row = 0, column = 0, padx = 10)
R2.grid(row = 0, column = 1, padx = 10)
R3.grid(row = 0, column = 2, padx = 10)

frame3 = Frame(top)
frame3.pack(fill = X)
space_frame3 = Frame(frame3, width = 10)
l5 = Label(frame3, text = "Processor Unit")
l6 = Label(frame3, text = "Script for test")
lb1 = Listbox(frame3, height = 7, exportselection = 0)
lb1.bind('<<ListboxSelect>>',getScript)
scrollbar = Scrollbar(frame3)
lb2 = Listbox(frame3, height = 7, width = 40, 
              yscrollcommand = scrollbar.set, exportselection = 0)

Everything goes fine as long as I've selected a radiobutton before selecting an item in Listbox. But every time I select another radio button, it return:

TypeError: getScript() takes exactly 1 argument (0 given)

Answer

Arthur Va&#239;sse picture Arthur Vaïsse · Oct 13, 2014

What happen when you select a Radiobutton is :

1) The intVar rb is set to the button value

2) The command getScript is called.

But, a Radiobutton selection do not generates any event, that's why there is 2 options in this case :

Call the function using a lambda function to provide a parameter as your command getScript expect one parameter ( that's the error message ).

R1 = Radiobutton(frame2, text = "Parallel Test",
                 variable = rb, value = 1,
                 command = lambda : getScript(None) )

An other option is - as it seem that your aim is to know what widget was selected - to use such a command:

R1 = Radiobutton(frame2, text = "Parallel Test",
                 variable = rb, value = 1,
                 command = lambda : getScript(R1) )

with your getSript function that takes a widget. Like this:

def getSript(widget):
    print widget["text"]