{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "8cd1e865-53d5-460b-8bae-5658e3aa3d16", "metadata": {}, "outputs": [], "source": [ "import panel as pn\n", "pn.extension()\n", "import requests\n", "import random\n", "from PIL import Image" ] }, { "cell_type": "code", "execution_count": null, "id": "ca65cc07-8181-4259-8770-9c780621eb78", "metadata": {}, "outputs": [], "source": [ "# Button widget\n", "run_button = pn.widgets.Button(name=\"Click to get a new image\")" ] }, { "cell_type": "code", "execution_count": null, "id": "8480d2c2-06c0-441e-9cf9-f858f2db1ec9", "metadata": {}, "outputs": [], "source": [ "def get_image(_):\n", " \"\"\"\n", " a function to generate random cat images\n", " \"\"\"\n", " api_url = 'https://api.thecatapi.com/v1/images/search'\n", " img_url = requests.get(api_url, stream=True).json()[0]['url']\n", " image = Image.open(requests.get(img_url, stream=True).raw)\n", " return pn.pane.Image(image, sizing_mode='scale_width')" ] }, { "cell_type": "code", "execution_count": null, "id": "6fd5a63f-012a-419c-8386-22b5b8ff243f", "metadata": {}, "outputs": [], "source": [ "# Bind the get_image function with the button widget\n", "interactive = pn.bind(get_image, run_button)" ] }, { "cell_type": "code", "execution_count": null, "id": "6e829400-320f-437c-8465-ed392afe3aa9", "metadata": {}, "outputs": [], "source": [ "desc = pn.pane.Markdown(\"\"\"\n", "# Hi there!\n", "Thanks for trying out the Panel template. This is a super simple demo that combines a function with a widget. \n", "Click the button below to generate a new cat image and check out https://panel.holoviz.org/\n", "to learn more.\n", "\"\"\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "84bfdf52-b6e0-400d-baaf-d16303a72b65", "metadata": {}, "outputs": [], "source": [ "# Layout using Template\n", "template = pn.template.FastListTemplate(\n", " title='Generate random cat images', \n", " sidebar=[desc, run_button],\n", " main=[interactive],\n", " accent_base_color=\"#88d8b0\",\n", " header_background=\"#88d8b0\",\n", ")\n", "template.servable()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" } }, "nbformat": 4, "nbformat_minor": 5 }