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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With