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

如何为shinyWidgets的treeInput节点添加图标或自定义图片?

给treeInput节点添加图标/自定义图片的方法

一、使用Font Awesome图标

shinyWidgets的treeInput支持直接使用Font Awesome图标,你需要手动修改create_tree生成的树结构,给目标节点添加icon属性,值为对应Font Awesome的完整类名(比如fa-solid fa-earth-europe)。

示例代码:

library(shiny)
library(shinyWidgets)

df <- data.frame(continent = c(rep("Europe", 2), rep("Asia", 2)),
                 country = c("France", "Germany", "China", "Japan"))

# 生成基础树结构
mytree <- create_tree(df, c("continent", "country"))

# 给大洲节点添加图标
mytree[[1]]$icon <- "fa-solid fa-earth-europe"  # 欧洲节点
mytree[[2]]$icon <- "fa-solid fa-earth-asia"    # 亚洲节点

# 给国家节点添加对应国旗图标
mytree[[1]]$children[[1]]$icon <- "fa-solid fa-flag-fr"  # 法国
mytree[[1]]$children[[2]]$icon <- "fa-solid fa-flag-de"  # 德国
mytree[[2]]$children[[1]]$icon <- "fa-solid fa-flag-cn"  # 中国
mytree[[2]]$children[[2]]$icon <- "fa-solid fa-flag-jp"  # 日本

ui <- fluidPage(
  # 手动引入最新版Font Awesome(若Shiny默认版本不足时使用)
  tags$head(tags$link(rel="stylesheet", href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css")),
  shinyWidgets::treeInput("mytree", "带图标的树形结构", mytree)
)

server <- function(input, output, session) {}

shinyApp(ui, server)

二、使用自定义本地图片(如旗帜图片)

如果要用自己的图片,需遵循Shiny的资源规则:把图片放在项目根目录的www文件夹下(Shiny会自动识别该目录),然后在节点的icon属性中用<img>标签指定图片路径和样式。

步骤:

  1. 在Shiny项目根目录创建www文件夹,将自定义图片(比如france.png、germany.png)放入其中。
  2. 修改树结构的icon属性为<img>标签,设置图片的尺寸、边距等样式。

示例代码:

library(shiny)
library(shinyWidgets)

df <- data.frame(continent = c(rep("Europe", 2), rep("Asia", 2)),
                 country = c("France", "Germany", "China", "Japan"))

mytree <- create_tree(df, c("continent", "country"))

# 给国家节点添加自定义旗帜图片
mytree[[1]]$children[[1]]$icon <- '<img src="france.png" style="width:20px; height:15px; margin-right:5px;">'
mytree[[1]]$children[[2]]$icon <- '<img src="germany.png" style="width:20px; height:15px; margin-right:5px;">'
mytree[[2]]$children[[1]]$icon <- '<img src="china.png" style="width:20px; height:15px; margin-right:5px;">'
mytree[[2]]$children[[2]]$icon <- '<img src="japan.png" style="width:20px; height:15px; margin-right:5px;">'

# 给大洲节点添加自定义图标
mytree[[1]]$icon <- '<img src="europe_icon.png" style="width:20px; height:20px; margin-right:5px;">'
mytree[[2]]$icon <- '<img src="asia_icon.png" style="width:20px; height:20px; margin-right:5px;">'

ui <- fluidPage(
  shinyWidgets::treeInput("mytree", "带自定义图片的树形结构", mytree)
)

server <- function(input, output, session) {}

shinyApp(ui, server)

注意事项:

  • Font Awesome的类名要对应正确版本,避免出现图标不显示的情况。
  • 自定义图片必须放在www文件夹下,路径直接写文件名即可,无需添加www/前缀。
  • 可通过<img>标签的style属性调整图片大小、边距,让图标与文字对齐更美观。

内容的提问来源于stack exchange,提问作者Lennyy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:31:16