![](/img/trans.png)
[英]how to use Tcl/Tk bind function on Tkinter's widgets in Python?
[英]Python - tkinter - How to capture bind function
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()
綁定函數不“返回”。 您的回調函數需要設置全局變量或調用其他函數。 例如:
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
(例如:將數據寫入磁盤,顯示錯誤,播放歌曲等),或者如何在其他函數中使用全局變量。
一般來說,如果您的應用程序片段是類的實例,則最容易完成這些事情-然后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?")
對於函數bind
, <Return>
並不意味着函數的return
。 相反,它確實意味着用戶按下了事件“ Enter key ”。
因此,如果您希望從messagebox
獲得響應,則可以使用其他方法來進行響應。 可能與您的messagebox
一起使用另一個StringVar()
選項,或使用任何全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.