0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python で画像を表示する(2)

Posted at

導入

今回は Web を使って画像を表示します。

前提

例によって仕事で普段使うようなフレームワークは面倒で嫌なので、Reflex というライブラリを使います。

準備

始めに Reflex をインストールします。

$ pip install reflex

適当なワークディレクトリを用意して reflex 用のプロジェクトを作成します。

$ reflex init

プロジェクトの種類を聞いてくるので blank (空っぽ)を選べば良いです。

表示したいイメージ (sample.png) はプロジェクトディレクトリ内の assets に置きます。

実行

$ reflex run

としたら、web ブラウザで http://localhost:3000/ にアクセスします。
デフォルトの画面が表示されたら OK です。

修正

当然ですがデフォルトで用意されたソースでは画像は表示してくれないので、
プロジェクトディレクトリにある project_name/project_name.py を修正します。

なんかディレクトリ名が冗長な気がするけども、今は気にしないでおきます。

def index() -> rx.Component:
    # Welcome Page (Index)
    return rx.container(
        rx.color_mode.button(position="top-right"),
        rx.vstack(
            rx.heading("Welcome to Reflex!", size="9"),
            rx.image(
                src="/sample.png",
                width="auto",
                height="auto"
            ),
            rx.text(
                "Get started by editing ",
                rx.code(f"{config.app_name}/{config.app_name}.py"),
                size="5",
            ),
            rx.link(
                rx.button("Check out our docs!"),
                href="https://reflex.dev/docs/getting-started/introduction/",
                is_external=True,
            ),
            spacing="5",
            justify="center",
            min_height="85vh",
        ),
        rx.logo(),
    )

このように rx.image(...) をねじ込んで保存します。
reflex はソースファイルを修正すると Web 画面のほうに即反映してくれます。

ただし reflex 実行中に assets 配下のファイルを変更しても即反映はしないようです。
reflex を Ctrl + C で一旦止めて、もう一度 reflex run すれば OK でした。

動作確認

「Welcome to Reflex!」の下に sample.png が表示されました。

次回(?)

これだけではあまりにつまらないので、テキストボックスとボタンを配置して
テキストボックスに入力したイメージをボタン押下で表示するとかやってみると良いかも知れません。

暇を持て余していたら続きをやるかも知れません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?