pywebio.output — Make output to web browser

This module provides functions to output all kinds of content to the user’s browser, and supply flexible output control.

Functions list

The following table shows the output-related functions provided by PyWebIO.
The functions marked with * indicate that they accept put_xxx calls as arguments.
The functions marked with indicate that they can use as context manager.

Name

Description

Output Scope

set_scope

Create a new scope

get_scope

Get the scope name in the runtime scope stack

clear

Clear the content of scope

remove

Remove the scope

scroll_to

Scroll the page to the scope

use_scope

Open or enter a scope

Content Outputting

put_text

Output plain text

put_markdown

Output Markdown

Output Messages.

put_html

Output html

put_link

Output link

put_processbar

Output a process bar

set_processbar

Set the progress of progress bar

put_loading

Output loading prompt

put_code

Output code block

put_table*

Output table

Output button and bind click event

put_image

Output image

put_file

Output a link to download a file

put_tabs*

Output tabs

put_collapse*†

Output collapsible content

put_scrollable*†

Output a fixed height content area,
scroll bar is displayed when the content
exceeds the limit

put_widget*

Output your own widget

Other Interactions

toast

Show a notification message

popup*†

Show popup

close_popup

Close the current popup window.

Layout and Style

put_row*†

Use row layout to output content

put_column*†

Use column layout to output content

put_grid*

Output content using grid layout

span

Cross-cell content

style*

Customize the css style of output content

Placeholder

output*

Placeholder of output

Output Scope

pywebio.output.set_scope(name, container_scope=None, position=- 1, if_exist=None)[source]

Create a new scope.

Parameters
  • name (str) – scope name

  • container_scope (str) – Specify the parent scope of this scope. When the scope doesn’t exist, no operation is performed.

  • position (int) – The location where this scope is created in the parent scope. (see Scope related parameters)

  • if_exist (str) –

    What to do when the specified scope already exists:

    • None: Do nothing

    • 'remove': Remove the old scope first and then create a new one

    • 'clear': Just clear the contents of the old scope, but don’t create a new scope

    Default is None

pywebio.output.get_scope(stack_idx=- 1)[source]

Get the scope name of runtime scope stack

Parameters

stack_idx (int) –

The index of the runtime scope stack. Default is -1.

0 means the top level scope(the ROOT Scope), -1 means the current Scope, -2 means the scope used before entering the current scope, …

Returns

Returns the scope name with the index, and returns None when occurs index error

pywebio.output.clear(scope=None)[source]

Clear the content of the specified scope

Parameters

scope (str) – Target scope name. Default is the current scope.

pywebio.output.remove(scope=None)[source]

Remove the specified scope

Parameters

scope (str) – Target scope name. Default is the current scope.

pywebio.output.scroll_to(scope=None, position='top')[source]

Scroll the page to the specified scope

Parameters
  • scope (str) – Target scope. Default is the current scope.

  • position (str) –

    Where to place the scope in the visible area of the page. Available value:

    • 'top' : Keep the scope at the top of the visible area of the page

    • 'middle' : Keep the scope at the middle of the visible area of the page

    • 'bottom' : Keep the scope at the bottom of the visible area of the page

pywebio.output.use_scope(name=None, clear=False, create_scope=True, **scope_params)[source]

Open or enter a scope. Can be used as context manager and decorator.

See User manual - use_scope()

Parameters
  • name (str) – Scope name. If it is None, a globally unique scope name is generated. (When used as context manager, the context manager will return the scope name)

  • clear (bool) – Whether to clear the contents of the scope before entering the scope.

  • create_scope (bool) – Whether to create scope when scope does not exist.

  • scope_params – Extra parameters passed to set_scope() when need to create scope. Only available when create_scope=True.

Usage

with use_scope(...) as scope_name:
    put_xxx()

@use_scope(...)
def app():
    put_xxx()

Content Outputting

Scope related parameters of output function

The output function will output the content to the “current scope” by default, and the “current scope” for the runtime context can be set by use_scope().

In addition, all output functions support a scope parameter to specify the destination scope to output:

with use_scope('scope3'):
    put_text('text1 in scope3')   # output to current scope: scope3
    put_text('text in ROOT scope', scope='ROOT')   # output to ROOT Scope

put_text('text2 in scope3', scope='scope3')   # output to scope3

The results of the above code are as follows:

text1 in scope3
text2 in scope3
text in ROOT scope

A scope can contain multiple output items, the default behavior of output function is to append its content to target scope. The position parameter of output function can be used to specify the insert position in target scope.

Each output item in a scope has an index, the first item’s index is 0, and the next item’s index is incremented by one. You can also use a negative number to index the items in the scope, -1 means the last item, -2 means the item before the last, …

The position parameter of output functions accepts an integer. When position>=0, it means to insert content before the item whose index equal position; when position<0, it means to insert content after the item whose index equal position:

with use_scope('scope1'):
    put_text('A')
    put_text('B', position=0)   # insert B before A -> B A
    put_text('C', position=-2)  # insert C after B -> B C A
    put_text('D', position=1)   # insert D before C B -> B D C A

Output functions

pywebio.output.put_text(*texts, sep=' ', inline=False, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output plain text

Parameters
  • texts – Texts need to output. The type can be any object, and the str() function will be used for non-string objects.

  • sep (str) – The separator between the texts

  • inline (bool) – Use text as an inline element (no line break at the end of the text). Default is False

  • scope (str) –

    The target scope to output. If the scope does not exist, no operation will be performed.

    Can specify the scope name or use a integer to index the runtime scope stack.

  • position (int) – The position where the content is output in target scope

For more information about scope and position parameter, please refer to User Manual

pywebio.output.put_markdown(mdcontent, strip_indent=0, lstrip=False, options=None, sanitize=True, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output Markdown

Parameters
  • mdcontent (str) – Markdown string

  • strip_indent (int) – For each line of mdcontent, if the first strip_indent characters are spaces, remove them

  • lstrip (bool) – Whether to remove the whitespace at the beginning of each line of mdcontent

  • options (dict) – Configuration when parsing Markdown. PyWebIO uses marked library to parse Markdown, the parse options see: https://marked.js.org/using_advanced#options (Only supports members of string and boolean type)

  • sanitize (bool) – Whether to use DOMPurify to filter the content to prevent XSS attacks.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

When using Python triple quotes syntax to output multi-line Markdown in a function, if you indent the Markdown text, you can use strip_indent or lstrip to prevent Markdown from parsing errors (But do not use strip_indent and lstrip at the same time):

# It is ugly without strip_indent or lstrip
def hello():
    put_markdown(r""" # H1
This is content.
""")

# Using lstrip to get beautiful indent
def hello():
    put_markdown(r""" # H1
    This is content.
    """, lstrip=True)

# Using strip_indent to get beautiful indent
def hello():
    put_markdown(r""" # H1
    This is content.
    """, strip_indent=4)
pywebio.output.put_info(*contents, closable=False, scope=None, position=- 1)Output:[source]
pywebio.output.put_success(*contents, closable=False, scope=None, position=- 1)Output:[source]
pywebio.output.put_warning(*contents, closable=False, scope=None, position=- 1)Output:[source]
pywebio.output.put_error(*contents, closable=False, scope=None, position=- 1)Output:[source]

Output Messages.

Parameters
  • contents – Message contents. The item is put_xxx() call, and any other type will be coverted to put_text(content).

  • closable (bool) – Whether to show a dismiss button on the right of the message.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

New in version 1.2.

pywebio.output.put_html(html, sanitize=False, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output HTML content

Parameters
  • html – html string

  • sanitize (bool) –

    Whether to use DOMPurify to filter the content to prevent XSS attacks.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Output hyperlinks to other web page or PyWebIO Application page.

Parameters
  • name (str) – The label of the link

  • url (str) – Target url

  • app (str) – Target PyWebIO Application name. See also: Server mode

  • new_window (bool) – Whether to open the link in a new window

  • scope, position (int) – Those arguments have the same meaning as for put_text()

The url and app parameters must specify one but not both

pywebio.output.put_processbar(name, init=0, label=None, auto_close=False, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output a process bar

Parameters
  • name (str) – The name of the progress bar, which is the unique identifier of the progress bar

  • init (float) – The initial progress value of the progress bar. The value is between 0 and 1

  • label (str) – The label of process bar. The default is the percentage value of the current progress.

  • auto_close (bool) – Whether to remove the progress bar after the progress is completed

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example:

import time

put_processbar('bar');
for i in range(1, 11):
    set_processbar('bar', i / 10)
    time.sleep(0.1)
pywebio.output.set_processbar(name, value, label=None)[source]

Set the progress of progress bar

Parameters
  • name (str) – The name of the progress bar

  • value (float) – The progress value of the progress bar. The value is between 0 and 1

  • label (str) – The label of process bar. The default is the percentage value of the current progress.

See also: put_processbar()

pywebio.output.put_loading(shape='border', color='dark', scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output loading prompt

Parameters
  • shape (str) – The shape of loading prompt. The available values are: 'border' (default)、 'grow'

  • color (str) – The color of loading prompt. The available values are: 'primary''secondary''success''danger''warning''info''light''dark' (default)

  • scope, position (int) – Those arguments have the same meaning as for put_text()

put_loading() can be used in 2 ways: direct call and context manager:

for shape in ('border', 'grow'):
    for color in ('primary', 'secondary', 'success', 'danger', 'warning', 'info', 'light', 'dark'):
        put_text(shape, color)
        put_loading(shape=shape, color=color)

# Use as context manager, the loading prompt will disappear automatically when the context block exits.
with put_loading():
    time.sleep(3)  # Some time-consuming operations
    put_text("The answer of the universe is 42")

# using style() to set the size of the loading prompt
put_loading().style('width:4rem; height:4rem')
pywebio.output.put_code(content, language='', rows=None, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output code block

Parameters
  • content (str) – code string

  • language (str) – language of code

  • rows (int) – The max lines of code can be displayed, no limit by default. The scroll bar will be displayed when the content exceeds.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

pywebio.output.put_table(tdata, header=None, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output table

Parameters
  • tdata (list) – Table data, which can be a two-dimensional list or a list of dict. The table cell can be a string or put_xxx() call. The cell can use the span() to set the cell span.

  • header (list) –

    Table header. When the item of tdata is of type list, if the header parameter is omitted, the first item of tdata will be used as the header. The header item can also use the span() function to set the cell span.

    When tdata is list of dict, header is used to specify the order of table headers, which cannot be omitted. In this case, the header can be a list of dict key or a list of (<label>, <dict key>).

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example:

# 'Name' cell across 2 rows, 'Address' cell across 2 columns
put_table([
    [span('Name',row=2), span('Address', col=2)],
    ['City', 'Country'],
    ['Wang', 'Beijing', 'China'],
    ['Liu', 'New York', 'America'],
])

# Use `put_xxx()` in `put_table()`
put_table([
    ['Type', 'Content'],
    ['html', put_html('X<sup>2</sup>')],
    ['text', '<hr/>'],
    ['buttons', put_buttons(['A', 'B'], onclick=...)],  
    ['markdown', put_markdown('`Awesome PyWebIO!`')],
    ['file', put_file('hello.text', b'hello world')],
    ['table', put_table([['A', 'B'], ['C', 'D']])]
])

# Set table header
put_table([
    ['Wang', 'M', 'China'],
    ['Liu', 'W', 'America'],
], header=['Name', 'Gender', 'Address'])

# When ``tdata`` is list of dict
put_table([
    {"Course":"OS", "Score": "80"},
    {"Course":"DB", "Score": "93"},
], header=["Course", "Score"])  # or header=[(put_markdown("*Course*"), "Course"), (put_markdown("*Score*") ,"Score")]

New in version 0.3: The cell of table support put_xxx() calls.

pywebio.output.span(content, row=1, col=1)[source]

Create cross-cell content in put_table() and put_grid()

Parameters
  • content – cell content. It can be a string or put_xxx() call.

  • row (int) – Vertical span, that is, the number of spanning rows

  • col (int) – Horizontal span, that is, the number of spanning columns

Example

put_table([
    ['C'],
    [span('E', col=2)],  # 'E' across 2 columns
], header=[span('A', row=2), 'B'])  # 'A' across 2 rows

put_grid([
    [put_text('A'), put_text('B')],
    [span(put_text('A'), col=2)],  # 'A' across 2 columns
])
pywebio.output.put_buttons(buttons, onclick, small=None, link_style=False, outline=False, group=False, scope=None, position=- 1, **callback_options)pywebio.io_ctrl.Output[source]

Output a group of buttons and bind click event

Parameters
  • buttons (list) –

    Button list. The available formats of list items are:

    • dict: {label:(str)button label, value:(str)button value, color:(str, optional)button color}

    • tuple or list: (label, value)

    • single value: label and value of option use the same value

    The value of button can be any JSON serializable object. The color of button can be one of: primary, secondary, success, danger, warning, info, light, dark.

    Example:

    put_buttons([dict(label='success', value='s', color='success')], onclick=...)  
    

  • onclick (callable / list) –

    Callback which will be called when button is clicked. onclick can be a callable object or a list of it.

    If onclick is callable object, its signature is onclick(btn_value). btn_value is value of the button that is clicked.

    If onclick is a list, the item receives no parameter. In this case, each item in the list corresponds to the buttons one-to-one.

    Tip: You can use functools.partial to save more context information in onclick.

    Note: When in Coroutine-based session, the callback can be a coroutine function.

  • small (bool) – Whether to use small size button. Default is False.

  • link_style (bool) – Whether to use link style button. Default is False

  • outline (bool) – Whether to use outline style button. Default is False

  • group (bool) – Whether to group the buttons together. Default is False

  • scope, position (int) – Those arguments have the same meaning as for put_text()

  • callback_options

    Other options of the onclick callback. There are different options according to the session implementation

    When in Coroutine-based Session:
    • mutex_mode: Default is False. If set to True, new click event will be ignored when the current callback is running. This option is available only when onclick is a coroutine function.

    When in Thread-based Session:
    • serial_mode: Default is False, and every time a callback is triggered, the callback function will be executed immediately in a new thread.

    If set serial_mode to True After enabling serial_mode, the button’s callback will be executed serially in a resident thread in the session, and all other new click event callbacks (including the serial_mode=False callback) will be queued for the current click event to complete. If the callback function runs for a short time, you can turn on serial_mode to improve performance.

Example:

from functools import partial

def row_action(choice, id):
    put_text("You click %s button with id: %s" % (choice, id))

put_buttons(['edit', 'delete'], onclick=partial(row_action, id=1))

def edit():
    put_text("You click edit button")
def delete():
    put_text("You click delete button")

put_buttons(['edit', 'delete'], onclick=[edit, delete])
pywebio.output.put_button(label, onclick, color=None, small=None, link_style=False, outline=False, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output a single button and bind click event to it.

Parameters
  • label (str) – Button label

  • onclick (callable) – Callback which will be called when button is clicked.

  • color (str) – The color of the button, can be one of: primary, secondary, success, danger, warning, info, light, dark.

  • small, link_style, outline, scope, position (-) – Those arguments have the same meaning as for put_buttons()

Example:

put_button("click me", onclick=lambda: toast("Clicked"), color='success', outline=True)

New in version 1.4.

pywebio.output.put_image(src, format=None, title='', width=None, height=None, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output image

Parameters
  • src – Source of image. It can be a string specifying image URL, a bytes-like object specifying the binary content of an image or an instance of PIL.Image.Image

  • title (str) – Image description.

  • width (str) – The width of image. It can be CSS pixels (like '30px') or percentage (like '10%').

  • height (str) – The height of image. It can be CSS pixels (like '30px') or percentage (like '10%'). If only one value of width and height is specified, the browser will scale image according to its original size.

  • format (str) – Image format, optinoal. e.g.: png, jpeg, gif, etc. Only available when src is non-URL

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example:

img = open('/path/to/some/image.png', 'rb').read()  
put_image(img, width='50px')

put_image('https://www.python.org/static/img/python-logo.png')
pywebio.output.put_file(name, content, label=None, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output a link to download a file

To show a link with the file name on the browser. When click the link, the browser automatically downloads the file.

Parameters
  • name (str) – File name downloaded as

  • content – File content. It is a bytes-like object

  • label (str) – The label of the download link, which is the same as the file name by default.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example:

content = open('./some-file', 'rb').read()  
put_file('hello-world.txt', content, 'download me')
pywebio.output.put_tabs(tabs, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output tabs.

Parameters
  • tabs (list) – Tab list, each item is a dict: {"title": "Title", "content": ...} . The content can be a string, the put_xxx() calls , or a list of them.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

put_tabs([
    {'title': 'Text', 'content': 'Hello world'},
    {'title': 'Markdown', 'content': put_markdown('~~Strikethrough~~')},
    {'title': 'More content', 'content': [
        put_table([
            ['Commodity', 'Price'],
            ['Apple', '5.5'],
            ['Banana', '7'],
        ]),
        put_link('pywebio', 'https://github.com/wang0618/PyWebIO')
    ]},
])

New in version 1.3.

pywebio.output.put_collapse(title, content=[], open=False, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output collapsible content

Parameters
  • title (str) – Title of content

  • content (list/str/put_xxx()) – The content can be a string, the put_xxx() calls , or a list of them.

  • open (bool) – Whether to expand the content. Default is False.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example:

put_collapse('Collapse title', [
    'text',
    put_markdown('~~Strikethrough~~'),
    put_table([
        ['Commodity', 'Price'],
        ['Apple', '5.5'],
    ])
], open=True)

put_collapse('Large text', 'Awesome PyWebIO! '*30)
pywebio.output.put_scrollable(content=[], height=400, keep_bottom=False, horizon_scroll=False, border=True, scope=None, position=- 1, **kwargs)pywebio.io_ctrl.Output[source]

Output a fixed height content area. scroll bar is displayed when the content exceeds the limit

Parameters
  • content (list/str/put_xxx()) – The content can be a string, the put_xxx() calls , or a list of them.

  • height (int/tuple) – The height of the area (in pixels). height parameter also accepts (min_height, max_height) to indicate the range of height, for example, (100, 200) means that the area has a minimum height of 100 pixels and a maximum of 200 pixels.

  • horizon_scroll (bool) – Whether to use the horizontal scroll bar

  • border (bool) – Whether to show border

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example:

import time

o = output("You can click the area to prevent auto scroll.")
put_scrollable(o, height=200, keep_bottom=True)

while 1:
    o.append(time.time())
    time.sleep(0.5)

Changed in version 1.1: add height parameter,remove max_height parameter; add keep_bottom parameter

pywebio.output.put_widget(template, data, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output your own widget

Parameters
  • template – html template, using mustache.js syntax

  • data (dict) –

    Data used to render the template.

    The data can include the put_xxx() calls, and the JS function pywebio_output_parse can be used to parse the content of put_xxx(). For string input, pywebio_output_parse will parse into text.

    ⚠️:When using the pywebio_output_parse function, you need to turn off the html escaping of mustache: {{& pywebio_output_parse}}, see the example below.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example

tpl = '''
<details {{#open}}open{{/open}}>
    <summary>{{title}}</summary>
    {{#contents}}
        {{& pywebio_output_parse}}
    {{/contents}}
</details>
'''

put_widget(tpl, {
    "open": True,
    "title": 'More content',
    "contents": [
        'text',
        put_markdown('~~Strikethrough~~'),
        put_table([
            ['Commodity', 'Price'],
            ['Apple', '5.5'],
            ['Banana', '7'],
        ])
    ]
})

Other Interactions

pywebio.output.toast(content, duration=2, position='center', color='info', onclick=None)[source]

Show a notification message.

Parameters
  • content (str) – Notification content.

  • duration (float) – The duration of the notification display, in seconds. 0 means not to close automatically (at this time, a close button will be displayed next to the message, and the user can close the message manually)

  • position (str) – Where to display the notification message. Available values are 'left', 'center' and 'right'.

  • color (str) – Background color of the notification. Available values are 'info', 'error', 'warn', 'success' or hexadecimal color value starting with '#'

  • onclick (callable) –

    The callback function when the notification message is clicked. The callback function receives no parameters.

    Note: When in Coroutine-based session, the callback can be a coroutine function.

Example:

def show_msg():
    put_text("You clicked the notification.")

toast('New messages', position='right', color='#2188ff', duration=0, onclick=show_msg)
pywebio.output.popup(title, content=None, size='normal', implicit_close=True, closable=True)[source]

Show a popup.

⚠️: In PyWebIO, you can’t show multiple popup windows at the same time. Before displaying a new pop-up window, the existing popup on the page will be automatically closed. You can use close_popup() to close the popup manually.

Parameters
  • title (str) – The title of the popup.

  • content (list/str/put_xxx()) – The content of the popup can be a string, the put_xxx() calls , or a list of them.

  • size (str) – The size of popup window. Available values are: 'large', 'normal' and 'small'.

  • implicit_close (bool) – If enabled, the popup can be closed implicitly by clicking the content outside the popup window or pressing the Esc key. Default is False.

  • closable (bool) – Whether the user can close the popup window. By default, the user can close the popup by clicking the close button in the upper right of the popup window. When set to False, the popup window can only be closed by popup_close(), at this time the implicit_close parameter will be ignored.

popup() can be used in 3 ways: direct call, context manager, and decorator.

  • direct call:

popup('popup title', 'popup text content', size=PopupSize.SMALL)

popup('Popup title', [
    put_html('<h3>Popup Content</h3>'),
    'html: <br/>',
    put_table([['A', 'B'], ['C', 'D']]),
    put_buttons(['close_popup()'], onclick=lambda _: close_popup())
])
  • context manager:

with popup('Popup title') as s:
    put_html('<h3>Popup Content</h3>')
    put_text('html: <br/>')
    put_buttons([('clear()', s)], onclick=clear)

put_text('Also work!', scope=s)

The context manager will open a new output scope and return the scope name. The output in the context manager will be displayed on the popup window by default. After the context manager exits, the popup window will not be closed. You can still use the scope parameter of the output function to output to the popup.

  • decorator:

@popup('Popup title')
def show_popup():
    put_html('<h3>Popup Content</h3>')
    put_text("I'm in a popup!")
    ...

show_popup()
pywebio.output.close_popup()[source]

Close the current popup window.

See also: popup()

Layout and Style

pywebio.output.put_row(content=[], size=None, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Use row layout to output content. The content is arranged horizontally

Parameters
  • content (list) – Content list, the item is put_xxx() call or None. None represents the space between the output

  • size (str) –

    Used to indicate the width of the items, is a list of width values separated by space.
    Each width value corresponds to the items one-to-one. (None item should also correspond to a width value).
    By default, size assigns a width of 10 pixels to the None item, and distributes the width equally to the remaining items.

    Available format of width value are:

    • pixels: like 100px

    • percentage: Indicates the percentage of available width. like 33.33%

    • fr keyword: Represents a scale relationship, 2fr represents twice the width of 1fr

    • auto keyword: Indicates that the length is determined by the browser

    • minmax(min, max) : Generate a length range, indicating that the length is within this range. It accepts two parameters, minimum and maximum. For example: minmax(100px, 1fr) means the length is not less than 100px and not more than 1fr

  • scope, position (int) – Those arguments have the same meaning as for put_text()

Example

# Two code blocks of equal width, separated by 10 pixels
put_row([put_code('A'), None, put_code('B')])

# The width ratio of the left and right code blocks is 2:3, which is equivalent to size='2fr 10px 3fr'
put_row([put_code('A'), None, put_code('B')], size='40% 10px 60%')
pywebio.output.put_column(content=[], size=None, scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Use column layout to output content. The content is arranged vertically

Parameters
  • content (list) – Content list, the item is put_xxx() call or None. None represents the space between the output

  • size (str) – Used to indicate the width of the items, is a list of width values separated by space. The format is the same as the size parameter of the put_row() function.

  • scope, position (int) – Those arguments have the same meaning as for put_text()

pywebio.output.put_grid(content, cell_width='auto', cell_height='auto', cell_widths=None, cell_heights=None, direction='row', scope=None, position=- 1)pywebio.io_ctrl.Output[source]

Output content using grid layout

Parameters
  • content – Content of grid, which is a two-dimensional list. The item of list is put_xxx() call or None. None represents the space between the output. The item can use the span() to set the cell span.

  • cell_width (str) – The width of grid cell.

  • cell_height (str) – The height of grid cell.

  • cell_widths (str) – The width of each column of the grid. The width values are separated by a space. Can not use cell_widths and cell_width at the same time

  • cell_heights (str) – The height of each row of the grid. The height values are separated by a space. Can not use cell_heights and cell_height at the same time

  • direction (str) –

    Controls how auto-placed items get inserted in the grid. Can be 'row'``(default) or ``'column' .

    'row' : Places items by filling each row
    'column' : Places items by filling each column

  • scope, position (int) – Those arguments have the same meaning as for put_text()

The format of width/height value in cell_width,``cell_height``,``cell_widths``,``cell_heights`` can refer to the size parameter of the put_row() function.

Example

put_grid([
    [put_text('A'), put_text('B'), put_text('C')],
    [None, span(put_text('D'), col=2, row=1)],
    [put_text('E'), put_text('F'), put_text('G')],
], cell_width='100px', cell_height='100px')
pywebio.output.style(outputs, css_style)Union[pywebio.io_ctrl.Output, pywebio.io_ctrl.OutputList][source]

Customize the css style of output content

Deprecated since version 1.3: See User Guide for new way to set css style for output.

Parameters
  • outputs (list/put_xxx()) – The output content can be a put_xxx() call or a list of it.

  • css_style (str) – css style string

Returns

The output contents with css style added:

Note: If outputs is a list of put_xxx() calls, the style will be set for each item of the list. And the return value can be used in anywhere accept a list of put_xxx() calls.

Example

style(put_text('Red'), 'color:red')

style([
    put_text('Red'),
    put_markdown('~~del~~')
], 'color:red')

put_table([
    ['A', 'B'],
    ['C', style(put_text('Red'), 'color:red')],
])

put_collapse('title', style([
    put_text('text'),
    put_markdown('~~del~~'),
], 'margin-left:20px'))

Placeholder

pywebio.output.output(*contents)[source]

Placeholder of output

output() can be passed in anywhere that put_xxx() can passed in. A handler it returned by output(), and after being output, the content can also be modified by the handler (See code example below).

Parameters

contents – The initial contents to be output. The item is put_xxx() call, and any other type will be coverted to put_text(content).

Returns

An OutputHandler instance, the methods of the instance are as follows:

  • reset(*contents) : Reset original contents to contents

  • append(*contents) : Append contents to original contents

  • insert(idx, *contents) : insert contents into original contents.

    when idx>=0, the output content is inserted before the element of the idx index.
    when idx<0, the output content is inserted after the element of the idx index.

Among them, the parameter contents is the same as output().

Example

hobby = output(put_text('Coding'))  # equal to output('Coding')
put_table([
   ['Name', 'Hobbies'],
   ['Wang', hobby]      # hobby is initialized to Coding
])

hobby.reset('Movie')  # hobby is reset to Movie
hobby.append('Music', put_text('Drama'))  # append Music, Drama to hobby
hobby.insert(0, put_markdown('**Coding**'))  # insert the Coding into the top of the hobby