如何在Bokeh中根据条件为按钮设置颜色?
Hey there! Let me walk through what went wrong with your initial code and how the solution you found fixes it.
Your Goal
You wanted a Bokeh button that changes color based on these priority-ordered rules:
- Red (#F81515) if any element in your color lists is red
- Orange (#FAB20A) if no red elements exist but there's orange
- Green (#088A08) only if all elements are green
What Was Wrong with Your Initial Code
Let's break down the key issues in your color-checking logic:
enumerate(color1 or color2 or color3 or color4)doesn’t work for your use case.color1 or color2just returns the first non-empty list, andenumerate()gives index-value pairs—not a single color string to compare against.- You had a typo:
colo2[k] = "#F81515"should becolor2[k] = "#F81515"(missing an 'r'), which would have caused errors when setting colors for the second list. - Your condition order was backwards: you checked for green first, but red should take highest priority.
Here's your original problematic code block for reference:
# Incorrect color check logic if enumerate(color1 or color2 or color3 or color4) == "#088A08": button = Button(label="success", button_type="success") elif enumerate(color1 or color2 or color3 or color4) == "#F81515": button = Button(label="danger", button_type="danger") else: button = Button(label="warning", button_type="warning")
The Correct Approach (Your Solution, Explained)
You nailed the fix by simplifying the logic—here's why it works:
- Combine All Color Lists: Merging
color1 + color2 + color3 + color4creates one master list of all color codes, so you can check every element at once. - Check in Priority Order:
- First check for red (highest priority)
- Then check for orange (only if no red is present)
- Fall back to green if neither red nor orange are found
Here's the core fixed code:
# Merge all color lists into one couleur = color1 + color2 + color3 + color4 # Check colors in priority order if "#F81515" in couleur: button = Button(label="danger", button_type="danger") elif "#FAB20A" in couleur: button = Button(label="warning", button_type="warning") else: button = Button(label="success", button_type="success")
Quick Extra Fix
Don't forget to correct that typo in your color2 loop:
# Original typo if abs(x) >= 1: colo2[k] = "#F81515" # Wrong variable name! # Fixed version if abs(x) >= 1: color2[k] = "#F81515"
Just to wrap up, make sure your full code includes all necessary imports (like pandas, numpy, and Bokeh components) and that you add the button to a Bokeh layout to display it properly.
内容的提问来源于stack exchange,提问作者Pythonic_FR
相关产品推荐
相关产品推荐

