2014-01-15 104 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()選項,或者使用任何全局變量。