Getting the selected value from combobox in Tkinter

49,082

I've figured out what's wrong in the code.

First, as James said the brackets should be removed when binding justamethod to the combobox.

Second, regarding the type error, this is because justamethod is an event handler, so it should take two parameters, self and event, like this,

def justamethod (self, event): 

After making these changes the code is working well.

Share:
49,082
Dania
Author by

Dania

Updated on July 09, 2022

Comments

  • Dania
    Dania almost 2 years

    I've made a simple combobox in python using Tkinter, I want to retrieve the value selected by the user. After searching, I think I can do this by binding an event of selection and call a function that will use something like box.get(), but this is not working. When the program starts the method is automatically called and it doesn't print the current selection. When I select any item from the combobox no method gets called. Here is a snippet of my code:

        self.box_value = StringVar()
        self.locationBox = Combobox(self.master, textvariable=self.box_value)
        self.locationBox.bind("<<ComboboxSelected>>", self.justamethod())
        self.locationBox['values'] = ('one', 'two', 'three')
        self.locationBox.current(0)
    

    This is the method that is supposed to be called when I select an item from the box:

    def justamethod (self):
        print("method is called")
        print (self.locationBox.get())
    

    Can anyone please tell me how to get the selected value?

    EDIT: I've corrected the call to justamethod by removing the brackets when binding the box to a function as suggested by James Kent. But now I'm getting this error:

    TypeError: justamethod() takes exactly 1 argument (2 given)

    EDIT 2: I've posted the solution to this problem.

    Thank You.

    • James Kent
      James Kent almost 9 years
      in your self.locationBox.bind you are calling the function by adding the brackets after the function name, remove these and it should work. so change self.justamethod() to self.justamethod
    • Dania
      Dania almost 9 years
      @JamesKent Thanks a lot, I always keep forgetting to remove the brackets. I removed them, but I'm getting this error, TypeError: justamethod() takes exactly 1 argument (2 given). Cany you please tell me how to solve it? Thanks.
    • James Kent
      James Kent almost 9 years
      the reason for the TypeError is because when the event is triggered, an event object is passed to the function you bound to as one of the arguments, if you want to see some of the attributes that can be got from this object, see this page: effbot.org/tkinterbook/tkinter-events-and-bindings.htm
  • Federico Dorato
    Federico Dorato about 4 years
    When answering, please provide an explanation of your code, and why it should solve the OP's problem. Thank you
  • Vikas Goel
    Vikas Goel about 2 years
    Could you please paste the full code? Thanks!