如何使用< ComboboxSelected>Tkinter虚拟事件 [英] How to use a <ComboboxSelected> virtual event with tkinter

查看:53
本文介绍了如何使用< ComboboxSelected>Tkinter虚拟事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 3.5.2中的tkk.Combobox主题小部件.我希望选择一个值时能够采取行动.

I am using a tkk.Combobox themed widget in Python 3.5.2. I want an action to happen when a value is selected.

在Python docs 中,它表示:

In the Python docs, it says:

当用户从值列表中选择一个元素时,组合框窗口小部件会生成一个<< ComboboxSelected>> 虚拟事件.

在堆栈上,有很多答案( 1 2 等):

Here on the Stack, there are a number of answers (1, 2, etc) that show how to bind the event:

cbox.bind("<<ComboboxSelected>>", function)

但是,我无法使其正常运行.这是一个非常简单的示例,展示了我无法正常运行的尝试:

However, I can't make it work. Here's a very simple example demonstrating my non-functioning attempt:

import tkinter as tk
from tkinter import ttk

tkwindow = tk.Tk()

cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)

cbox.bind("<<ComboboxSelected>>", print("Selected!"))

tkwindow.mainloop()

我得到一个"Selected!"的实例.立即运行此代码,即使没有单击任何东西.但是,当我实际上在组合框中选择某些内容时,什么也没发生.

I get one instance of "Selected!" immediately when I run this code, even without clicking anything. But nothing happens when I actually select something in the combobox.

我在Windows 7中使用IDLE,以防万一.

I'm using IDLE in Windows 7, in case it makes a difference.

我想念什么?

推荐答案

问题不在于事件<< ComboboxSelected>> ,而是 bind 函数需要将回调作为第二个参数.

The problem is not with the event <<ComboboxSelected>>, but the fact that bind function requires a callback as second argument.

当您这样做:

cbox.bind("<<ComboboxSelected>>", print("Selected!"))

您基本上是将调用结果分配给 print("Selected!")作为回调.

you're basically assigning the result of the call to print("Selected!") as callback.

要解决您的问题,您可以简单地分配一个函数对象,以在事件发生时调用(选项1,这是可取的),也可以使用 lambda 函数(选项2).

To solve your problem, you can either simply assign a function object to call whenever the event occurs (option 1, which is the advisable one) or use lambda functions (option 2).

这是选项1:

import tkinter as tk
from tkinter import ttk

tkwindow = tk.Tk()

cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)


def callback(eventObject):
    print(eventObject)

cbox.bind("<<ComboboxSelected>>", callback)

tkwindow.mainloop()

请注意不存在<代码>()后<代码>回调在:<代码> cbox.bind( << ComboboxSelected>>" 中,回调).

这是选项2:

import tkinter as tk
from tkinter import ttk

tkwindow = tk.Tk()

cbox = ttk.Combobox(tkwindow, values=[1,2,3], state='readonly')
cbox.grid(column=0, row=0)

cbox.bind("<<ComboboxSelected>>", lambda _ : print("Selected!"))

tkwindow.mainloop()

检查什么是lambda函数以及如何使用它们!

Check what are lambda functions and how to use them!

查看本文以了解有关事件和绑定的更多信息:

Check this article to know more about events and bindings:

http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

这篇关于如何使用&lt; ComboboxSelected&gt;Tkinter虚拟事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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