我已经创建了一个小示例,它显示了工作和不工作的情况。工作示例:
import ipywidgets as widgets
selected = {}
a = widgets.Dropdown(description="Apple", options = ["a","k"])
b = widgets.Dropdown(description="Boeing", options = ["a",'b'])
c = widgets.Dropdown(description="Coco Cola", options = ["a",'b','c'])
def getvaluea(change):
selected["a"] = change.new
with out:
out.clear_output()
print(selected)
def getvalueb(change):
selected["b"] = change.new
with out:
out.clear_output()
print(selected)
def getvaluec(change):
selected["c"] = change.new
with out:
out.clear_output()
print(selected)
out = widgets.Output()
tab = widgets.Tab()
tab.children = [a,b,c]
tab.titles = ["a",'b','c']
a.observe(getvaluea, 'value')
b.observe(getvalueb, 'value')
c.observe(getvaluec, 'value')
display(tab)
display(out)
使用此代码示例将更改选定的add或change items。当我试图将相同的代码样本包装在一个类中时,我在获取结果时遇到了问题。
class UserInterfaceAttempt10:
def __init__(self):
self.selected = {}
self.a = widgets.Dropdown(description="Apple", options = ["a","k"])
self.b = widgets.Dropdown(description="Boeing", options = ["a",'b'])
self.c = widgets.Dropdown(description="Coco Cola", options = ["a",'b','c'])
self.out = widgets.Output()
self.tab = widgets.Tab()
self.tab.children = [self.a, self.b, self.c]
self.tab.titles = ["a",'b','c']
self.a.observe(self.getvaluea)
self.b.observe(self.getvalueb)
self.c.observe(self.getvaluec)
def getvaluea(self, change):
self.selected["a"] = change.new
with self.out:
self.out.clear_output()
print(self.selected)
def getvalueb(self, change):
self.selected["b"] = change.new
with self.out:
self.out.clear_output()
print(self.selected)
def getvaluec(self, change):
self.selected["c"] = change.new
with self.out:
self.out.clear_output()
print(self.selected)
def display_GUI(self):
display(self.tab)
display(self.out)
ob = UserInterfaceAttempt10()
ob.display_GUI()
有人能帮我理解这个问题吗?谢谢!
发布于 2021-11-12 12:39:43
与许多小部件问题一样,打印和调试是您的好帮手。
如果你在你的getvalue
方法中使用print(change)
,你会看到这个问题:
该函数被多次调用,只有一次小部件更改。最后一个变化是持久存在的变化。
相反,如果您的observe调用指定:
self.a.observe(self.getvaluea, names='value')
您应该会看到所需的结果:
https://stackoverflow.com/questions/69944120
复制相似问题