gpt4 book ai didi

python - IPywidgets 观察包裹在一个类中时不起作用

转载 作者:行者123 更新时间:2023-12-05 04:41:53 25 4
gpt4 key购买 nike

我创建了一个小示例,它显示了工作情况和非工作情况。工作示例,

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)

使用此代码示例将更改添加或更改所选项目。当我尝试将相同的代码示例包装在一个类中时,我在获取结果时遇到了问题。

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()

有人可以帮助我理解这个问题吗?谢谢!

最佳答案

与许多小部件问题一样,打印和调试是您的 friend 。

如果您在其中一个 getvalue 方法中print(change),您将看到问题:

enter image description here

只需更改一个小部件,该函数就会被多次调用。最后一个更改是持续存在的更改。

如果您的观察调用指定:

self.a.observe(self.getvaluea, names='value')

您应该会看到想要的结果:

enter image description here

关于python - IPywidgets 观察包裹在一个类中时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69944120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com