【问题标题】:Python Button Bind two functions and send arguments with the bindingPython Button 绑定两个函数并通过绑定发送参数
【发布时间】:2011-09-11 07:11:49
【问题描述】:

我对 python 还是有点陌生​​,并且正在开发一个包含 GUI 的项目。我经常使用 Tkinter 和按钮,并且很好奇是否有一种方法可以通过绑定运行函数,因为我希望在按下时发生一件事,在释放时发生另一件事。

        s = str(x+1) + ":" + str(y+1)
        img = ImageTk.PhotoImage(Image.open('button.png'))
        b = Tkinter.Button(field_hid, image=img, borderwidth=0, highlightthickness=0, background='grey')
        b.bind("<ButtonPress-1>", lambda s=s, button=b: location_down(event,s,button))
        b.bind("<ButtonRelease-1>", lambda s=s, button=b: location_up(event,s,button))
        b.img = img
        b.pack()
        b.grid(row=x, column=y)

我不明白我该怎么做,因为唯一可以传递给函数的是事件,但我的程序需要参数。

【问题讨论】:

    标签: python events button tkinter bind


    【解决方案1】:

    使用 bind 的唯一方法是让它调用一个函数。当您使用lambda 时,您只是在创建一个匿名函数。您可以轻松做到:

    b.bind("<ButtonPress-1>", self.SomeOtherFunction)
    

    lambda 在您想向函数传递附加参数时很有用。与使用 command 选项时不同,使用绑定可以获得包含大量有用信息的事件对象,因此您可能不需要传递任何其他信息。

    例如,您可以这样做:

    def OnPress(event):
        print "widget %s was pressed" % event.widget
    def OnRelease(event):
        print "widget %s was released" % event.widget
    
    b = Button(...)
    b.bind("<ButtonPress-1>", OnPress)
    b.bind("<ButtonRelease-1>", OnRelease)
    

    有关绑定的详细介绍,请参阅 effbot.org 上的 Events and Bindings

    【讨论】:

    • 谢谢,lambdas 很有趣
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    相关资源
    最近更新 更多