PyScript を使うと、HTMLファイルの中でPythonコードを書いて、ブラウザ上で実行することができます。以下は、PyScriptの簡単な使用例です。

必要な準備

PyScriptを使うためには、HTMLファイルにPyScriptのライブラリを読み込む必要があります。以下のようにセットアップします。

1. 基本のHTMLファイル

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PyScriptの基本例</title>
    <!-- PyScriptのライブラリを読み込む -->
    <link rel="stylesheet" href="<https://pyscript.net/latest/pyscript.css>">
    <script defer src="<https://pyscript.net/latest/pyscript.js>"></script>
</head>
<body>

<h1>PyScriptでPythonを実行</h1>

<!-- Pythonコードを書くエリア -->
<py-script>
    print("こんにちは、PyScriptの世界へ!")
</py-script>

</body>
</html>

説明

2. ユーザー入力の例

ユーザーからの入力を取得し、PyScriptで処理する例です。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PyScriptの入力例</title>
    <link rel="stylesheet" href="<https://pyscript.net/latest/pyscript.css>">
    <script defer src="<https://pyscript.net/latest/pyscript.js>"></script>
</head>
<body>

<h2>数字を入力して、その二乗を計算します</h2>

<input id="number" type="number" placeholder="数字を入力">
<button id="calculate">計算する</button>
<p id="result"></p>

<py-script>
    def calculate_square(event):
        number = int(Element("number").value)
        result = number ** 2
        Element("result").element.innerText = f"結果: {result}"

    Element("calculate").element.onclick = calculate_square
</py-script>

</body>
</html>

説明

3. グラフ描画の例

PyScriptとPythonのライブラリを使って、グラフを描画します。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PyScriptでグラフを描画</title>
    <link rel="stylesheet" href="<https://pyscript.net/latest/pyscript.css>">
    <script defer src="<https://pyscript.net/latest/pyscript.js>"></script>
</head>
<body>

<h2>PyScriptでMatplotlibのグラフを描画</h2>

<py-script>
    import matplotlib.pyplot as plt

    # データの準備
    x = [1, 2, 3, 4, 5]
    y = [1, 4, 9, 16, 25]

    # グラフの描画
    plt.plot(x, y)
    plt.title("Simple Plot")
    plt.xlabel("X軸")
    plt.ylabel("Y軸")
    plt.show()
</py-script>

</body>
</html>

説明