You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Bokeh中根据条件为按钮设置颜色?

Fixing Bokeh Button Color Based on Multiple List Values

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:

  1. enumerate(color1 or color2 or color3 or color4) doesn’t work for your use case. color1 or color2 just returns the first non-empty list, and enumerate() gives index-value pairs—not a single color string to compare against.
  2. You had a typo: colo2[k] = "#F81515" should be color2[k] = "#F81515" (missing an 'r'), which would have caused errors when setting colors for the second list.
  3. 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:

  1. Combine All Color Lists: Merging color1 + color2 + color3 + color4 creates one master list of all color codes, so you can check every element at once.
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:14:28