从Tkinter的组合框中获取选定的值 [英] Getting the selected value from combobox in Tkinter

查看:115
本文介绍了从Tkinter的组合框中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

编辑:我已经纠正了对justamethod的调用,方法是将框绑定到James Kent建议的函数时去掉了方括号。但是现在我得到了这个错误:

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()恰好接受1个参数(给定2个参数)

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

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

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

谢谢。

推荐答案

我知道出了什么问题在代码中。

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

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

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

第二,关于类型错误,这是因为justamethod是事件处理程序,因此应采用两个参数,self和event,像这样,

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.

这篇关于从Tkinter的组合框中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆