【Dash】Hello World

一、最简单的 Dash

Building and launching an app with Dash can be done with just 5 lines of code.

Open a Python IDE on your computer, create an app.py file with the code below and install Dash if you haven't done so already. To launch the app, type into your terminal the command pythonapp.py. Then go to the http link.

Alternatively, with Dash 2.11 or later, you can run this app and other examples from this documentation in a Jupyter Notebook.

The code below creates a very small "Hello World" Dash app.

from dash import Dash, html

app = Dash()

app.layout = html.Div(children=['Hello World'])

if __name__ == '__main__':
    app.run(debug=True)

二、解读

from dash import Dash, html
    app = Dash()
  • 从 dash 模块中导入 Dash 类 和 html 组件库。
  • 创建一个 Dash 实例,命名为 app。
app.layout = html.Div(children=['Hello World'])
  • 设置 Dash 应用布局。app.layout 是一个属性,定义了Dash 应用的 UI 结构。
  • 这里的布局被设置为一个 html.Div 组件,它是个容器,用于包裹其他 HTML 元素。
  • children 参数接收一个字符串列表,输出‘Hellow World’。

if __name__ == '__main__':
    app.run(debug=True)
  • app.run() 启动 Dash 应用。
  • run 方法启动一个本地服务器,允许你访问和交互你的Dash 应用。
  • debug = True 参数启动调试模式。代码改变时会重新加载应用,如果出现错误会提供更多的调试信息。

三、html.Div() 是什么意思?

这是 Dash 库中的一个函数,用于创建一个 HTML<div> 标签的组件。在 Dash 以及更广泛的 Web 开发中,<div> 是一个通用的容器元素,用在 HTML 文档中分组和组织内容。

在 Dash 中,html.Div() 函数通常用于以下目的: 

  1. 布局容器:作为其他组件的容器,帮助组织应用的布局结构。
  2. 样式和类:可以通过 className 或 style 属性来设置 <div> 的 CSS 类或内嵌样式,从而控制其外观和布局。
  3. 响应式设计:与 CSS 框架(如 Bootstrap)结合使用,<div> 可以创建响应式布局,以适应不同的屏幕尺寸和设备。
  4. 嵌套组件:html.Div() 可以包含文本、其他 HTML 组件或 Dash 组件,支持嵌套结构。
  5. 动态内容:html.Div() 的 children 属性可以是静动态的文本或组件,也可以是动态生成的内容,如回调函数的输出。

带有 CSS 类和内嵌样式的 html.Div() 示例:

from dash import Dash, html

app = Dash()

app.layout = html.Div(
    # 给外层 div 设置一个类名
    className='container',
    children=[
        # 创建一个 div 元素,其中包含文本 'Styled Div'
        html.Div(
            children='Styled Div',
            # 给这个 div 设置一个类名
            className='my-div-class',
            # 内嵌样式,设置文本颜色为蓝色,字体大小为 20px
            style={'color': 'blue', 'fontSize': '20px'}
        ),
        # 可以继续添加更多组件...
    ]
)

# 运行应用
if __name__ == '__main__':
    app.run(debug=True)

  • 19
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值