我打算回傳 gameMode 的值,因為我想使用 gameMode 的輸出來作為我正在做的游戲的簡單中等或困難,但總是存在名稱錯誤。有沒有辦法解決這個問題?錯誤圖片:在此處輸入圖片描述
from ipywidgets import Button, HBox
Modes = ['Easy', 'Medium','Hard']
switch = [Button(description=name) for name in Modes]
combined = HBox([items for items in switch])
def upon_clicked(btn):
gameMode=btn.description.lower()
for n in range(len(Modes)):
switch[n].style.button_color = 'gray'
btn.style.button_color = 'pink'
for n in range(len(Modes)):
switch[n].on_click(upon_clicked)
display(combined)
gameMode
uj5u.com熱心網友回復:
您需要從 on_click 處理程式回傳一個值,或者能夠設定一個屬性。使用執行“on_click”的函式的回傳輸出作為基本示例,您可以執行以下操作:
from ipywidgets import widgets, HBox
from IPython.display import display
from traitlets import traitlets
output = widgets.Output()
class LoadedButton(widgets.Button):
"""A button that can holds a value as a attribute."""
def __init__(self, value=None, *args, **kwargs):
super(LoadedButton, self).__init__(*args, **kwargs)
# Create the value attribute.
self.add_traits(value=traitlets.Any(value))
self.style.button_color="gray"
buttons = [
LoadedButton(description="Easy", value="easy"),
LoadedButton(description="Medium", value="medium"),
LoadedButton(description="Hard", value="hard")
]
def change_btn_color(btn):
output.clear_output()
for button in buttons:
button.style.button_color="gray"
btn.style.button_color = 'pink'
with output:
print(btn.value)
for button in buttons:
button.on_click(change_btn_color)
combined = HBox(buttons)
display(combined, output)
單擊按鈕后,在下一個單元格中,您可以提取按鈕的輸出:
print(output.outputs[0]["text"])
我以前從未使用過 ipywidgets,所以希望其他人可以提出更好的解決方案,但這確實有效
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425266.html
標籤:Python 按钮 jupyter-笔记本 小部件
上一篇:單擊按鈕時填寫日期欄位
