2014-01-15 58 views
0
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函数的返回值?Python - tkinter - 如何捕获绑定函数

我已经试过:

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

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

回答

2

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

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(例如做的:将数据写入到磁盘,显示错误,播放歌曲等),或者你想在其他功能中如何使用全局变量。

1

一般来说,这些东西是最容易实现,如果你的应用程序的作品是一个类的实例 - 然后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?") 
+0

你可以建议一种方法来做到这一点,而不需要创建一个类吗? – Phoenix

+0

@Robert - 全局或可变模块级变量实际上是唯一的其他选项。 – mgilson

0

对于函数bind,该<Return>并不意味着功能的return。相反,它意味着用户按下的事件“Enter key”。

所以,如果你喜欢得到messagebox的回应,那么你可以用其他方式做到这一点。可能与您的messagebox使用另一个StringVar()选项,或者使用任何全局变量。