Ben*_*wen 4 ipython ipywidgets
我正在尝试“widgetize”我的 IPython 笔记本,但遇到了事件和从函数返回值的问题。这是我认为最好的工作流程:
我首先尝试使用“interact”方法来调用函数,但这似乎很难关联事件和返回值。从阅读其他交互式示例来看,创建一个类似乎是要走的路。我不经常写课;所以希望我的错误很简单。
下面制作了两个小部件,当用户按下“Enter”键时应该调用一个函数并将其返回值存储在类中以备将来使用。
实际上,它在我输入任何文本之前两次触发该函数,并在我更改值时抛出“unicode object is not callable”。
import ipywidgets as widgets
from IPython.display import display
def any_function_returning_value(word1,word2):
new_word = 'Combining words is easy: %s %s'%(word1,word2)
print new_word
return new_word
class learn_classes_and_widgets():
def __init__(self, param1 = 'a word', param2 = 'another word'):
self.p1_text = widgets.Text(description = 'Word #1',value = param1)
self.p2_text = widgets.Text(description = 'Word #2',value = param2)
self.p1_text.on_submit(self.handle_submit())
self.p2_text.on_submit(self.handle_submit())
display(self.p1_text, self.p2_text)
def handle_submit(self):
print "Submitting"
self.w = any_function_returning_value(self.p1_text.value,self.p2_text.value)
return self.w
f = learn_classes_and_widgets(param1 = 'try this word')
#f.w should contain the combined words when this is all working
Run Code Online (Sandbox Code Playgroud)
Oliver Ruebel 通过电子邮件回答。这是他对我的问题的修复。
分配给 on_submit 是错误的
当您调用 on.submit 函数时,您需要将要调用的函数交给它。在您的代码中,这看起来像这样。
self.p1_text.on_submit(self.handle_submit())
self.p2_text.on_submit(self.handle_submit())
Run Code Online (Sandbox Code Playgroud)
但是,您的代码所做的是调用 self.handle_submit (因为您在函数后包含了“()”括号),然后将该函数的返回值分配给您的提交句柄。这解释了您所看到的行为。即,该函数在您的init () 中被调用两次,然后当事件发生时,它尝试对函数返回的字符串进行操作。解决这个问题很简单,只需删除“()”,即:
self.p1_text.on_submit(self.handle_submit)
self.p2_text.on_submit(self.handle_submit)
Run Code Online (Sandbox Code Playgroud)
handle_submit 函数签名错误
句柄提交函数必须接受小部件的文本对象作为输入。即,您将获得 self.p1_text 或 self.p2_text 作为输入,具体取决于哪个小部件调用它。即,您的函数应如下所示:
def handle_submit(self, text):
...
Run Code Online (Sandbox Code Playgroud)
通过上述更改,一切都应该按预期工作。但是,如果您想为不同的小部件实现不同的行为,您应该为不同的小部件使用不同的句柄函数,并将任何共享行为放入由句柄函数调用的其他函数中。
import ipywidgets as widgets
from IPython.display import display
def any_function_returning_value(word1,word2):
new_word = 'Combining words is easy: %s %s'%(word1,word2)
print new_word
return new_word
class learn_classes_and_widgets():
def __init__(self, param1 = 'a word', param2 = 'another word'):
self.p1_text = widgets.Text(description = 'Word #1',value = param1)
self.p2_text = widgets.Text(description = 'Word #2',value = param2)
self.p1_text.on_submit(self.handle_submit)
self.p2_text.on_submit(self.handle_submit)
display(self.p1_text, self.p2_text)
def handle_submit(self, text):
print "Submitting"
print "Text " + str(text.value)
self.w = any_function_returning_value(self.p1_text.value,self.p2_text.value)
return self.w
f = learn_classes_and_widgets(param1 = 'try this word')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4682 次 |
| 最近记录: |