【问题标题】:Python - tkinter - How to capture bind functionPython - tkinter - 如何捕获绑定函数
【发布时间】:2014-02-04 05:53:38
【问题描述】:
from tkinter import StringVar, messagebox, Entry, Tk

def accept(event):
    acceptInput=messagebox.askquestion("Input Assessment","do you accept this input?")
    return acceptInput

window=Tk()
userInput=StringVar()
e=Entry(window,textvariable=userInput)
e.pack()
e.bind('<Return>',accept)
window.mainloop()

我的问题是:如何捕获accept函数的返回值?

我试过了:

e.bind('<Return>',a=accept.get())

a=e.bind('<Return>',accept).get()

【问题讨论】:

    标签: python python-3.x tkinter return


    【解决方案1】:

    绑定函数不会“返回”。您的回调需要设置一个全局变量或调用其他函数。例如:

    def accept(event):
        global acceptInput
        acceptInput=messagebox.askquestion("Input Assessment","do you accept this input?")
    

    ...或...

    def accept(event):
        acceptInput=messagebox.askquestion("Input Assessment", "do you accept this input?")
        do_something(acceptInput)
    

    您可以在do_something 中定义您想要做什么(例如:将数据写入磁盘、显示错误、播放歌曲等),或者您希望如何在某些应用中使用全局变量其他功能。

    【讨论】:

      【解决方案2】:

      一般来说,如果你的应用程序是一个类的实例,这些事情是最容易完成的——然后accept 可以只在类上设置一个属性。在这种情况下,您可能希望在 Entry 中绑定该功能:

      class AcceptEntry(Entry):
          def __init__(self, *args, **kwargs):
              Entry.__init__(self, *args, **kwargs)
              self.bind('<Return>', self.accept)
              self.acceptInput = None
      
          def accept(self, event):
              self.acceptInput = messagebox.askquestion("Input Assessment",
                                                        "do you accept this input?")
      

      【讨论】:

      • 你能建议一种不创建类的方法吗?
      • @Robert -- 全局或可变模块级变量实际上是唯一的其他选择。
      【解决方案3】:

      对于函数bind&lt;Return&gt; 并不意味着函数的return。相反,它确实意味着用户按下的事件“Enter key”。

      所以,如果您想从messagebox 获得回复,那么您可以通过其他方式进行。可能将另一个 StringVar() 选项与您的 messagebox 一起使用,或使用任何全局变量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 2013-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多