在Tkinter中获取下拉框的选定值

10

我用Tkinter在Python中制作了一个简单的组合框,我想检索用户选择的值。经过搜索,我认为可以通过绑定选择事件并调用一个函数来完成这个任务,该函数将使用类似于box.get()的内容,但是这并没有起作用。当程序启动时,该方法会自动调用,并且不打印当前选择。当我从组合框中选择任何项目时,都不会调用任何方法。以下是我的代码片段:

    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)

这是当我从框中选择一个项目时应该调用的方法:

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

有人可以告诉我如何获取所选值吗?

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

TypeError:justamethod()需要恰好1个参数(给出2个)

编辑2:我已经发布了解决此问题的方法。

谢谢。


3
在您的 self.locationBox.bind 函数中,您通过在函数名称后面添加括号来调用该函数,去掉这些括号应该就可以正常工作。因此,请将 self.justamethod() 更改为 self.justamethod - James Kent
1
@JamesKent 非常感谢,我总是忘记去掉括号。我已经去掉了,但是出现了这个错误:TypeError: justamethod()需要1个参数,但给出了2个。你能告诉我如何解决吗?谢谢。 - Dania
TypeError 的原因是当事件被触发时,一个事件对象会作为参数之一传递给绑定的函数。如果您想查看可以从此对象获取的一些属性,请参阅此页面:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm - James Kent
2个回答

14

我已经找出代码的问题所在。

首先,正如James所说,绑定combobox时应该移除括号。

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

def justamethod (self, event): 

经过这些修改,代码运行良好。


请问您能否粘贴完整的代码?谢谢! - Coder

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

3
当回答问题时,请提供您的代码解释以及为什么它能够解决提问者的问题。谢谢。 - Federico Dorato

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接