Tkinter 将带有参数event的函数绑定到控件

原文:Tkinter binding a function with arguments to a widget    python - Tkinter binding a function with arguments to a widget - Stack OverflowTkinter binding a function with arguments to a widget    

Tkinter widgets are the building blocks that come with some predefined operations. To handle a specific functionality of an application, we bind the keys to some widgets.

We can bind an event to widgets using the bind(‘key’, callback function) method. Key represents the event through which we target a particular event, whereas callable function activates the event. To create a callback function, we switch to a specific widget as the argument and then add the particular event.

Example

Let us understand this with an example where we have to bind the <Enter> key with a function that displays some text on the window. Whenever the button is clicked or <Enter> key is pressed, the callback function executes and the event happens.

#Import the Tkinter library
from tkinter import *
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x250")
#Define Event handlers with arguments
def event_show(event):
   button.config(bg="red", fg= "white")
   label.config(text="Hello World")
#Create a Label
label= Label(win, text="",font=('Helvetica 15 underline'))
label.pack()
#Create a frame
frame= Frame(win)
#Create Buttons in the frame
button= Button(frame, text="Click",command=lambda:event_show(button))
button.pack(pady=10)
frame.pack()
#Bind the function
win.bind('<Return>',lambda event:event_show(event))
#注意两行红色代码处lambda函数的差别
win.mainloop()

Output

Running the above code will display a window that contains a button. The button event can bed triggered through two ways − Enter Key and Click Event.

Now, press Enter or click the button to display the output on the screen.

———————————————————————————————————————————

另一篇文章stackoverflow:

当您使用 bind 创建绑定时,Tkinter 会自动添加一个包含有关事件信息的event参数。 您需要在 rand_func 定义或如何调用它时考虑到这一点。

使用 command 属性时不包含此参数。 您必须注意在每种情况下如何调用函数或函数如何解释其参数时考虑到这个额外的参数。

以下是一种解决方案,它在绑定中使用 lambda 仅在使用 bind 命令时接受额外事件,但不将其传递给最终命令。

import tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.frame = tk.Frame(self)
        self.frame.pack()
        self.button = tk.Button(self.frame, text="click me",
                             command=lambda a=1, b=2, c=3: 
                                self.rand_func(a, b, c))
        self.button.pack()
        self.frame.bind("<Return>", 
                        lambda event, a=10, b=20, c=30: 
                            self.rand_func(a, b, c))
        # make sure the frame has focus so the binding will work
        self.frame.focus_set()

    def rand_func(self, a, b, c):
        print "self:", self, "a:", a, "b:", b, "c:", c
        print (a+b+c)

app = SampleApp()
app.mainloop()

话虽如此,绑定到框架是正确的做法很少见。 通常一个框架不会有键盘焦点,除非它有焦点,否则绑定永远不会触发。 如果您要设置全局绑定,您应该绑定到“all”绑定标签(使用 bind_all 方法)或顶层控件。 

需要注意的是,自动添加包含事件信息的参数仅适用于由 bind 方法绑定的回调。 那些与command 有关(在构造函数中或与 configure() 绑定)不会收到此类事件对象。 这种区别在文档中不容易发现(至少我还没有找到),但具体可以看这篇回答:python - What is the difference between command and bind in tkinter? - Stack Overflow

对于command属性:button控件的command仅用于“单击按钮”event,并且不接收任何参数。 对于bind方法:任何控件都可以bind一堆不同类型的event,并且总是将 event 对象作为唯一的参数传递。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值