从 Tkinter 的组合框中获取选定的值

Getting the selected value from combobox in Tkinter

我使用 Tkinter 在 python 中制作了一个简单的组合框,我想检索用户 select 编辑的值。搜索后,我想我可以通过绑定 selection 的事件并调用一个将使用类似 box.get() 的函数来实现,但这不起作用。当程序启动时,该方法会自动调用,并且不会打印当前的 selection。当我 select 组合框中的任何项目时,不会调用任何方法。这是我的代码片段:

    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)

这是当我 select 从盒子中取出一个物品时应该调用的方法:

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

谁能告诉我如何获得 selected 值?

编辑:我已按照 James Kent 的建议,通过在将框绑定到函数时删除括号来更正对 justamethod 的调用。但是现在我收到了这个错误:

TypeError:justamethod() 恰好接受 1 个参数(给定 2 个)

编辑 2:我已经发布了这个问题的解决方案。

谢谢。

我已经弄清楚代码中有什么问题了。

首先,正如 James 所说,在将 justamethod 绑定到组合框时应删除括号。

其次,关于类型错误,这是因为justamethod是一个事件处理器,所以它应该带两个参数,self和event,像这样,

def justamethod (self, event): 

进行这些更改后,代码运行良好。

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()