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

查看:32
本文介绍了从 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?

我已经按照 James Kent 的建议将框绑定到函数时删除了括号,从而更正了对 justmethod 的调用.但现在我收到此错误:

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: justamemethod() 只需要 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 所说,在将 justmethod 绑定到组合框时应该删除括号.

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

其次,关于类型错误,这是因为justmethod是一个事件处理器,所以它应该带两个参数,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天全站免登陆