Reputation: 1688
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.
Upvotes: 10
Views: 69883
Reputation: 49
from tkinter import ttk
from tkinter import messagebox
from tkinter import Tk
root = Tk()
root.geometry("400x400")
#^ width - heghit window :D
cmb = ttk.Combobox(root, width="10", values=("prova","ciao","come","stai"))
#cmb = Combobox
class TableDropDown(ttk.Combobox):
def __init__(self, parent):
self.current_table = tk.StringVar() # create variable for table
ttk.Combobox.__init__(self, parent)# init widget
self.config(textvariable = self.current_table, state = "readonly", values = ["Customers", "Pets", "Invoices", "Prices"])
self.current(0) # index of values for current table
self.place(x = 50, y = 50, anchor = "w") # place drop down box
def checkcmbo():
if cmb.get() == "prova":
messagebox.showinfo("What user choose", "you choose prova")
elif cmb.get() == "ciao":
messagebox.showinfo("What user choose", "you choose ciao")
elif cmb.get() == "come":
messagebox.showinfo("What user choose", "you choose come")
elif cmb.get() == "stai":
messagebox.showinfo("What user choose", "you choose stai")
elif cmb.get() == "":
messagebox.showinfo("nothing to show!", "you have to be choose something")
cmb.place(relx="0.1",rely="0.1")
btn = ttk.Button(root, text="Get Value",command=checkcmbo)
btn.place(relx="0.5",rely="0.1")
root.mainloop()
Upvotes: 1
Reputation: 1688
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.
Upvotes: 14