<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python | アリッシアの朝</title>
	<atom:link href="https://alicia-ing.com/category/programming/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://alicia-ing.com</link>
	<description></description>
	<lastBuildDate>Mon, 11 Aug 2025 12:13:58 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.3</generator>

<image>
	<url>https://alicia-ing.com/wp-content/uploads/2023/05/cropped-alicia-32x32.webp</url>
	<title>Python | アリッシアの朝</title>
	<link>https://alicia-ing.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】進捗バーを自作、作成する方法｜tqdmの使い方</title>
		<link>https://alicia-ing.com/programming/python/tqdm-progress-bar/</link>
					<comments>https://alicia-ing.com/programming/python/tqdm-progress-bar/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Sun, 01 Dec 2024 22:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=8257</guid>

					<description><![CDATA[Pythonで処理する際に、どれだけ処理が完了したのかコンソール画面に表示します。進捗バー（プログレスバー）を作成したい方に向けて、tqdmを使用した進捗表示の方法を解説します。 本記事では、tqdmの基本の使い方や実際 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<p>Pythonで進捗バーを表示する。</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="1920" height="1000" src="https://alicia-ing.com/wp-content/uploads/2024/12/complete.gif" alt="実行例" class="wp-image-8266"/></figure>
</div></div>



<p>Pythonで処理する際に、どれだけ<strong>処理が完了したのかコンソール画面に表示</strong>します。<br>進捗バー（プログレスバー）を作成したい方に向けて、tqdmを使用した進捗表示の方法を解説します。</p>



<p>本記事では、tqdmの基本の使い方や実際のソースコードを例示し、<br>処理の進捗をわかりやすく表示する方法を紹介します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>Pythonで進捗バーを使いたい人</li>



<li>処理の進捗を視覚的に表示したい開発者</li>



<li>大量データを処理する際の進捗表示をスマートに実装したい方</li>



<li>tqdmの基本的な使い方を覚えたい人</li>



<li>Pythonで自動化処理を行う際に進捗ゲージを追加したい方</li>



<li>処理時間が長い作業の進捗をわかりやすく表示したい方</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">tqdmとは</h2>



<figure class="wp-block-image size-full"><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/12/tqdm.webp" alt="tqdmについて" class="wp-image-8268" srcset="https://alicia-ing.com/wp-content/uploads/2024/12/tqdm.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/12/tqdm-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/12/tqdm-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/12/tqdm-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>モジュールtqdmは、<strong>処理の進捗を視覚的に表示するための便利なライブラリ</strong>です。</p>



<p>大量のデータや複数の処理を行う際、その進捗を表示することで、<br><strong>開発者やユーザーに安心感を提供</strong>します。</p>



<p>進捗表示を使うことで、大規模なプロジェクトや複雑なタスクでも、<br>現在どの程度進行しているのかを一目で把握できるようになります。</p>



<p>例えば、データ処理の際にも、どれくらいの作業が完了したか、<br><strong>予定に対してどれだけ進んでいるのかを視覚化</strong>することが可能です。</p>



<p>tqdmをインストールするには、pipを使用します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>pip install tqdm</code></pre></div>



<h3 class="wp-block-heading">基本的な機能</h3>



<p>基本的な使い方としては、<strong>forループにtqdmを追加するだけ</strong>で、<br>簡単に進捗バーを表示することができます。</p>



<p>tqdmは、処理の進行状況を正確に視覚化するだけでなく、<br>プログラムのパフォーマンスにほとんど負担をかけずに自然に表示できるので、非常に便利です。</p>



<p>また、進捗をリアルタイムで確認できるため、<br>長時間の処理でもユーザーに安心感を与えることができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from tqdm import tqdm
import time

for i in tqdm(range(10), desc=&quot;Processing&quot;):
    time.sleep(0.5)  # 一時停止を作る</code></pre></div>



<p>このコードでは、10回のループを繰り返している間に進捗バーが表示されます。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>timeモジュールのsleep関数を使ったカウントダウンタイマーを解説しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/countdown-timer/" title="【Python】カウントダウンタイマー｜sleepでタイマー処理" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/02/countdown-timer-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/02/countdown-timer-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/02/countdown-timer-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/02/countdown-timer-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】カウントダウンタイマー｜sleepでタイマー処理</div><div class="blogcard-snippet internal-blogcard-snippet">Pythonでのタイマーとカウントダウンの作り方は、tkinterを使用してsleep関数とtimerを組み合わせ、使いやすいタイマーを実装できます。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.08.11</div></div></div></div></a>
</div>



<p><strong>descを使って処理内容を説明</strong>することで、<br>何をしているのかをユーザーにわかりやすく伝えることができます。</p>



<p>これにより、ユーザーにも進行状況が伝わり、処理が進んでいる感覚を共有できます。</p>



<h2 class="wp-block-heading">すべての処理の完了率をゲージで表示</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/12/completion-rate.webp" alt="完了率表示" class="wp-image-8269" srcset="https://alicia-ing.com/wp-content/uploads/2024/12/completion-rate.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/12/completion-rate-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/12/completion-rate-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/12/completion-rate-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>指定されたフォルダ内の画像ファイルを<strong>WebP形式に変換する処理</strong>を実行します。</p>



<p>処理は、フォルダ内のファイルを順次ループし、<br>PillowライブラリのImage関数を使って画像をWebP形式に変換します。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>webpに一括変換を解説しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/image-conversion/" title="【Python】pngやjpgの画像をwebpに一括で画像変換" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/06/image-conversion-1-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/06/image-conversion-1-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/06/image-conversion-1-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/06/image-conversion-1-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】pngやjpgの画像をwebpに一括で画像変換</div><div class="blogcard-snippet internal-blogcard-snippet">pngやjpeg、bmpを画像変換するためにフリーソフトを探しても求めるものがないときはPythonのpillow,osモジュールで一括でwebpにします。自作ならwindows、macの対応を気にせず、応用でheicやavifもできます。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.08.11</div></div></div></div></a>
</div>



<p>その際、<strong>tqdmを用いて進捗状況を一歩ずつ表示し、処理の完了までの時間を視覚化</strong>しています。</p>



<p>これにより、処理がどの程度進んでいるかを簡単に把握することができ、<br>使用者や開発者が実行時間を予測したり、<strong>処理の進行を確認することが可能</strong>です。</p>



<p>また、処理中にエラーが発生した場合、どのファイルで問題が発生したのかを明確に特定できるため、トラブルシューティングも容易です。</p>



<h3 class="wp-block-heading">ソースコード・解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「PIL (Pillow)」：Python Imaging Library（PIL）を拡張したPillowモジュールは、画像ファイルの読み込みや保存、編集を行うために必要です。インストールは「pip install Pillow」を使用します。<br>「os」：ファイルやディレクトリのパス操作を行うために必要です。特にフォルダの存在確認やファイルのパス取得に使用します。<br>「tqdm」：長時間実行する処理の進捗状況を視覚的に表示するために必要です。インストールは「pip install tqdm」を使用します。<br>「time」：処理に微小な遅延を持たせるために必要です。これにより進捗バーが滑らかに動くように見せる効果があります。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from PIL import Image
import os
from tqdm import tqdm
import time</code></pre></div>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「input_folder」：変換対象となる画像ファイルが格納されているフォルダのパスです。<br>「output_folder」：変換後の画像ファイルを保存するためのフォルダのパスです。<br>「file_list」：入力フォルダ内の変換対象画像ファイルのリストです。<br>「progress_bar」：tqdmによって生成される進捗バーオブジェクトで、処理の進捗を視覚的に表示するためのものです。<br>「input_path」：入力画像ファイルの絶対パスです。<br>「output_path」：変換後のWebP形式の画像ファイルの絶対パスです。</p>



<ul class="wp-block-list">
<li><strong>convert_to_webp関数</strong></li>
</ul>



<p>この関数は、指定されたフォルダ内の画像ファイルをWebP形式に変換する処理を行います。</p>



<p>最初に出力フォルダが存在しない場合は新たに作成し、<br>入力フォルダ内の画像ファイルを拡張子でフィルタリングして取得します。</p>



<p>取得したファイルリストを使って、<strong>一つずつ画像ファイルを開き</strong>、<br>WebP形式に変換して出力フォルダに保存します。</p>



<p><strong>処理の進捗状況はtqdmで表示</strong>し、<br>全てのファイルが処理されるとメッセージを表示します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>def convert_to_webp(input_folder, output_folder):
    # 出力フォルダが存在しない場合は作成する
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # フォルダ内のファイルを取得する
    file_list = [f for f in os.listdir(input_folder) if f.lower().endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;, &#39;.gif&#39;, &#39;.bmp&#39;))]

    # ファイル数が0の場合、処理を終了
    if not file_list:
        print(&quot;画像ファイルが見つかりませんでした。&quot;)
        return

    # tqdmで進捗バーを作成
    progress_bar = tqdm(total=len(file_list), desc=&quot;変換中&quot;, unit=&quot;file&quot;, smoothing=0.1)

    for file_name in file_list:
        # ファイルの絶対パスを取得する
        input_path = os.path.join(input_folder, file_name)
        output_path = os.path.join(output_folder, os.path.splitext(file_name)[0] + &#39;.webp&#39;)

        # 画像を開いてWebP形式で保存する
        try:
            with Image.open(input_path) as image:
                image.save(output_path, &#39;webp&#39;)
        except Exception as e:
            print(f&quot;エラー: {file_name} ({e})&quot;)

        # 進捗バーを更新
        progress_bar.update(1)
        time.sleep(0.01)  # 流れる感覚を持たせるための微小な遅延

    progress_bar.close()
    print(&quot;全ての画像の変換が完了しました！&quot;)

# フォルダのパスを指定して変換を実行する
input_folder = &#39;Input&#39;
output_folder = &#39;Output&#39;

convert_to_webp(input_folder, output_folder)</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h2 class="wp-block-heading">実演</h2>



<p>プログラムを実行すると、冒頭で示したような進捗バーが表示されます。</p>



<p>本記事での例では、画像変換なのであまり進捗バーの役割を成さないですが、<br><strong>動画や人工知能などの大きいデータを扱う場合は進捗バー</strong>があるとプログラムが動いているのか把握できます。</p>



<p>必要に応じて、プログレスバーを導入してください。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>本記事では、Pythonで進捗バーを作成するためのライブラリ、tqdmの使い方を解説しました。</p>



<p>既存のスクリプトにtqdmを実装することで、処理の進捗を視覚的に確認しながら、<br>効率的に作業を進めることが可能になります。</p>



<p>tqdmを使うことで、従来の処理に比べてよりユーザーフレンドリーな体験を提供し、<br>開発者は実行中の処理を可視化しやすくなり、デバッグや評価時の助けにもなります。</p>



<p>次回の開発では、さらに複雑な処理にもこの進捗表示を実装して、便利さを向上させていきましょう。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/tqdm-progress-bar/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】Google-Text-to-SpeechのAPIを取得し発話</title>
		<link>https://alicia-ing.com/programming/python/google-text-to-speech/</link>
					<comments>https://alicia-ing.com/programming/python/google-text-to-speech/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Sun, 24 Nov 2024 22:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=8095</guid>

					<description><![CDATA[GoogleのText-to-Speech APIを使えば、Pythonを用いて簡単にテキストを音声に変換できます。 本記事では初めての方にも分かりやすく、APIの取得方法からPythonでの実装までを詳しく解説していき [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<p>Google Text-to-SpeechをPythonから制御する。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="1000" src="https://alicia-ing.com/wp-content/uploads/2024/11/complete-1.gif" alt="" class="wp-image-8220"/></figure>
</div></div>



<p>GoogleのText-to-Speech APIを使えば、<br><strong>Pythonを用いて簡単にテキストを音声に変換</strong>できます。</p>



<p>本記事では初めての方にも分かりやすく、<br><strong>APIの取得方法からPythonでの実装</strong>までを詳しく解説していきます。</p>



<p>また、商用利用や料金、音声ファイルの保存方法など、<br>Pythonで自動音声生成を行う手順を完全に理解できる内容となっています。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>Pythonでテキストを音声に変換したい方</li>



<li>Google Text-to-Speechを使って多言語対応の発話システムを作りたい方</li>



<li>商用プロジェクトで音声合成を利用したいと考えている方</li>



<li>音声データを自動生成してMP3形式で保存したい方</li>



<li>教育コンテンツや自動ナレーションを簡単に作成したい方</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">Google Text-to-Speechとは</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1.webp" alt="Text-to-Speechについて" class="wp-image-8223" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>Google Text-to-Speechはテキストを音声に変換するサービスで、<br>無料で使える発話エンジンです。</p>



<p>日本語、英語、フランス語など、<strong>多くの言語に対応</strong>していて幅広い用途で利用できます。</p>



<p>Pythonと組み合わせることで、さまざまな<strong>音声アプリケーションを簡単に作成</strong>できます。<br>たとえば、ナビゲーションシステムや教育アプリ、自動応答システムなど用途は無限大です。</p>



<p>Google Text-to-SpeechはAI技術を駆使して、<strong>自然で高品質な音声を生成</strong>します。<br>これにより、ユーザーにとって使いやすく、聞き心地の良い音声を提供することが可能です。</p>



<p>また、Text-to-Speechはアクセントや話者のトーンなども調整可能なため、<br>さまざまな音声タイプをカスタマイズできます。</p>



<h3 class="wp-block-heading">Google Text-to-Speechの使い方</h3>



<p>Google Text-to-Speechを使うには、まず<strong>Google Cloudのアカウントを作成</strong>し、<br>Text-to-Speechを有効にする必要があります。</p>



<p>Pythonのプログラムから音声合成を行うためには、<br><strong>Google Cloudの認証情報（APIキー）を取得して設定する</strong>必要があります。</p>



<p>Pythonコードを用いることで、<strong>指定したテキストを音声に変換</strong>し、<br><strong>WAVやMP3形式で保存することが可能</strong>です。</p>



<p>これにより、手軽に音声ガイドやナレーションを自動生成することができます。<br>例えば、観光案内アプリでの音声案内や教育用の教材など、多種多様な用途で活用できます。</p>



<p>また、テキストの内容に基づいて<strong>発話速度やピッチも調整できる</strong>ため、<br>さまざまなシチュエーションに対応した音声を生成することが可能です。</p>



<h3 class="wp-block-heading">Google Text-to-Speechは商用利用できる？</h3>



<p>Google Text-to-Speechは<strong>商用利用も可能</strong>です。<br>ただし、Google Cloudの使用量に応じた料金が発生するため、<br><strong>商用プロジェクトで利用する際は料金体系に十分注意</strong>する必要があります。</p>



<p>また、Googleの利用規約に従って、適切に利用することが求められます。</p>



<p>商用利用する場合、特に注意すべきなのは<strong>利用料金と使用制限</strong>です。<br>料金は使用量に依存しているため、大量に音声を生成する場合は予算に応じて計画的に使うことが求められます。API使用数を確認しながら調整する必要があります。</p>



<p>また、商用利用に際しては、エンドユーザーに対する<strong>情報提供やプライバシーの保護</strong>に対しても責任を持つ必要があります。これらを十分に理解したうえで、商用利用を進めることが大切です。</p>



<h4 class="wp-block-heading">pyttsx3との比較</h4>



<p>合成音声pyttsx3の場合は、PC搭載の読み上げ機能を使うためAPIを必要としません。<br>ただし、<strong>pyttsx3自体は商用利用できます</strong>が、読み上げソフトが商用利用できません。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>pyttsx3の使い方を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/pyttsx3-text-to-speech/" title="【Python】合成音声pyttsx3使い方-テキストを読み上げ" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】合成音声pyttsx3使い方-テキストを読み上げ</div><div class="blogcard-snippet internal-blogcard-snippet">Pythonの合成音声ライブラリ「pyttsx3」の基本的な使い方とその機能について。pyttsx3は、テキストの読み上げから、音声ファイルの生成、プロパティの変更に対応します。さらに、商用利用可能（ソフトは別途）や日本語、英語に対応。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2024.11.26</div></div></div></div></a>
</div>



<p>要するに、個人で合成音声を使いたい場合は、pyttsx3を使用して、<br>ゲームやアプリのナレーションに追加したい場合は、<br><strong>Google Text-to-Speechを使う</strong>必要があります。</p>



<h3 class="wp-block-heading">Google Text-to-Speechの料金（無料枠）は？</h3>



<p>無料枠の利用では、<strong>月に400万文字（WaveNetは100万文字）</strong>まで音声合成が可能です。<br>それを<strong>超えた場合は従量課金制</strong>で料金が発生します。</p>



<p>商用利用を検討している場合、<a target="_self" href="https://cloud.google.com/text-to-speech/pricing?hl=ja">Google Cloudの料金表</a>を確認し、<br>必要な予算を見積もっておくことが重要です。</p>



<p>料金は、使用する声の種類や文字数に依存します。<br>例えば、<strong>標準的な音声とWaveNet音声</strong>（より自然な音声）では料金が異なります。</p>



<p>WaveNet音声はより高品質ですが、<strong>その分料金が高く</strong>なります。<br>また、<strong>使用する言語や地域によっても料金が変動</strong>することがありますので、<br>事前に詳細を確認することをお勧めします。</p>



<p>Google Cloudの無料利用枠を活用することで、コストを抑えながらプロトタイプを作成したり、個人プロジェクトで利用する際には、<strong>無料枠で十分対応できるケースが多い</strong>です。</p>



<p>ビジネス規模での利用に関しては、必要な予算を正確に把握し、<br>適切なプランを選択することが重要です。</p>



<h3 class="wp-block-heading">Google Text-to-SpeechはMP3保存できる？</h3>



<p>Google Text-to-Speechの音声合成はをMP3形式で保存することが可能です。</p>



<p>Pythonからテキストを取得して、そのままMP3またはWAV形式で保存することができます。この機能を使うことで、簡単に<strong>ナレーション用の音声ファイルを生成する</strong>ことが可能になります。</p>



<p>例えば、教育コンテンツやオーディオブックの自動生成に<strong>MP3保存機能を活用</strong>することができます。音声ファイルは高音質で保存され、聞き取りやすいものとなります。</p>



<p>また、MP3形式で保存することで、さまざまなデバイスで再生可能な音声ファイルを作成することができます。これにより、<strong>ユーザーの利便性を高める</strong>ことができ、プロジェクトの成功に寄与します。</p>



<p><strong>WAV形式に比べてMP3形式はファイルサイズが小さい</strong>ため、<br>オンラインでの共有やストレージの節約にも有利です。</p>



<p>Pythonを使用して<strong>MP3形式に保存する</strong>ことで、<br>音声ファイルの管理が簡単になり、アプリケーションの効率的な運用が可能となります。</p>



<p>作成した動画にナレーションを入れたい場合、<br><strong>moviepyを併用する</strong>ことで、簡単にナレーション音声を導入できます。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>moviepyの機能をまとめています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/moviepy/" title="【Python】moviepyできること｜mp3・GIF編集変換" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2024/11/moviepy-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/moviepy-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/11/moviepy-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/11/moviepy-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】moviepyできること｜mp3・GIF編集変換</div><div class="blogcard-snippet internal-blogcard-snippet">MoviePyで動画編集を自動化！Pythonでカット、結合、リサイズからGIF変換まで簡単に行えるMoviePyの基本から応用的な使い方を徹底解説。動画編集を効率化したいプログラマーやSNS素材作成に挑戦したい方におすすめのガイドです。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2024.11.22</div></div></div></div></a>
</div>



<h2 class="wp-block-heading">Google Text-to-Speechの登録方法</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/how_to_register.webp" alt="アカウント作成について" class="wp-image-8224" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/how_to_register.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/how_to_register-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/how_to_register-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/how_to_register-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>Google Text-to-Speechを使うにはまずGoogle Cloudのアカウントを作成します。<br>「Google Cloud」にアクセスして、<strong>アカウント情報や支払い方法を入力</strong>します。</p>



<p>Cloud Speech-to-Textを有効にして、APIを取得します。</p>



<h3 class="wp-block-heading">アカウント作成</h3>



<p>「<a target="_self" href="https://cloud.google.com/text-to-speech/?hl=ja">Text-to-Speechの無料トライアル</a>」にアクセスし、Googleアカウントを用いてログインします。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1879" height="953" src="https://alicia-ing.com/wp-content/uploads/2024/11/register_account.webp" alt="アカウント作成" class="wp-image-8205" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/register_account.webp 1879w, https://alicia-ing.com/wp-content/uploads/2024/11/register_account-300x152.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/register_account-1024x519.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/register_account-768x390.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/11/register_account-1536x779.webp 1536w" sizes="(max-width: 1879px) 100vw, 1879px" /></figure>



<p>アカウント作成する際に、<strong>支払い方法を登録</strong>（クレジットカード・デビットカードなど）する必要があります。</p>



<p>既に、Google広告やアドセンスに登録している場合は、再度追加しなくてもよいです。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1884" height="1064" src="https://alicia-ing.com/wp-content/uploads/2024/11/register_card.webp" alt="" class="wp-image-8206" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/register_card.webp 1884w, https://alicia-ing.com/wp-content/uploads/2024/11/register_card-300x169.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/register_card-1024x578.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/register_card-768x434.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/11/register_card-1536x867.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/11/register_card-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/11/register_card-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/11/register_card-320x180.webp 320w" sizes="(max-width: 1884px) 100vw, 1884px" /></figure>



<p><br>アカウント作成が完了したら、Google Cloudのさまざまなサービスを利用するための準備が整います。</p>



<p>プロジェクトの管理は、<strong>Google Cloudコンソールから</strong>簡単に行えます。<br>プロジェクトの概要や利用状況の確認、APIの有効化など、必要な操作を行うことで、プロジェクトをスムーズに進められます。</p>



<h3 class="wp-block-heading">Text-to-Speechを有効にする</h3>



<p>ハンバーガーメニューから「APIとサービス&gt;ライブラリ」に移動して、<br>「<strong>Cloud Text-to-Speech API</strong>」を有効にします。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1884" height="934" src="https://alicia-ing.com/wp-content/uploads/2024/11/library.webp" alt="ライブラリの場所" class="wp-image-8208" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/library.webp 1884w, https://alicia-ing.com/wp-content/uploads/2024/11/library-300x149.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/library-1024x508.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/library-768x381.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/11/library-1536x761.webp 1536w" sizes="(max-width: 1884px) 100vw, 1884px" /></figure>



<p>見つけることができない場合は、検索バーから探します。</p>



<div class="wp-block-cocoon-blocks-sticky-box blank-box block-box sticky st-red">
<p>Cloud <strong>Speech-to-Text</strong> APIというものがあります。<br>こちらは発話から文字に起こします。<br><strong>動画の音声を字幕を自動で書き起こしたい</strong>ときに使えます。</p>
</div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1884" height="875" src="https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech.webp" alt="APIを有効" class="wp-image-8209" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech.webp 1884w, https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-300x139.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1024x476.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-768x357.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1536x713.webp 1536w" sizes="(max-width: 1884px) 100vw, 1884px" /></figure>



<p>APIの有効化後、実際に音声合成のリクエストを行えるようになります。APIの有効化は簡単に行うことができ、あとは<strong>必要な認証情報を設定する</strong>ことでPythonから操作が可能です。</p>



<h3 class="wp-block-heading">.jsonのAPIを取得</h3>



<p>サイドバーから「IAMと管理&gt;サービスアカウント」に進み、<br>サービスアカウントを作成します。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1468" height="1080" src="https://alicia-ing.com/wp-content/uploads/2024/11/service_account.webp" alt="" class="wp-image-8210" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/service_account.webp 1468w, https://alicia-ing.com/wp-content/uploads/2024/11/service_account-300x221.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/service_account-1024x753.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/service_account-768x565.webp 768w" sizes="(max-width: 1468px) 100vw, 1468px" /></figure>



<p>詳細情報に、サービスアカウント名を設定します。<br>指定すると<strong>自動でサービスアカウントIDが生成</strong>されます。</p>



<p>そのほかの情報は<strong>省略可能</strong>ですので、そのままで大丈夫です。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1835" height="1080" src="https://alicia-ing.com/wp-content/uploads/2024/11/account_detail.webp" alt="" class="wp-image-8211" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/account_detail.webp 1835w, https://alicia-ing.com/wp-content/uploads/2024/11/account_detail-300x177.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/account_detail-1024x603.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/account_detail-768x452.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/11/account_detail-1536x904.webp 1536w" sizes="(max-width: 1835px) 100vw, 1835px" /></figure>



<p>作成後、「操作」の3点マークから「<strong>鍵を管理</strong>」に進みます。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1558" height="1027" src="https://alicia-ing.com/wp-content/uploads/2024/11/make_key.webp" alt="" class="wp-image-8212" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/make_key.webp 1558w, https://alicia-ing.com/wp-content/uploads/2024/11/make_key-300x198.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/make_key-1024x675.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/make_key-768x506.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/11/make_key-1536x1012.webp 1536w" sizes="(max-width: 1558px) 100vw, 1558px" /></figure>



<p>「キー」タブから「鍵を追加」を選択して、<br><strong>JSONファイルを作成</strong>します。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="1080" src="https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API.webp" alt="" class="wp-image-8213" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API.webp 1920w, https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API-300x169.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API-1024x576.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API-768x432.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API-1536x864.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API-320x180.webp 320w" sizes="(max-width: 1920px) 100vw, 1920px" /></figure>



<p>JSONファイルには、<strong>APIにアクセスするための認証情報</strong>が含まれています。</p>



<p>このファイルを適切に管理することで、安全にGoogle Cloudのサービスを利用することが可能です。Pythonスクリプトからこのファイルを参照することで、<br><strong>音声合成のリクエストを安全に行う</strong>ことができます。</p>



<h2 class="wp-block-heading">PythonでGoogle Text-to-Speechを操作</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/operation.webp" alt="Pythonで動かすには" class="wp-image-8225" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/operation.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/operation-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/operation-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/operation-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>Google Text-to-Speech APIをPythonで操作することで、<br>CSVファイルに格納したテキストを音声ファイルに変換することができます。</p>



<p>CSVのA列に英単語を格納してそれを一行ずつ読み込んで音声合成し、<br><strong>WAVファイルとして保存</strong>することが可能です。</p>



<p>Pythonを使うことで、<strong>業務での自動化や学習教材の作成</strong>など、さまざまなシーンで活用できます。<br>特に、複数のテキストを一括で音声化したい場合に便利です。</p>



<p>例えば、数百行にわたるテキストデータを<strong>自動で音声ファイルに変換</strong>し、<br>ナレーションやガイドとして利用することができます。</p>



<p>手作業で音声を録音する<strong>手間を大幅に削減する</strong>ことができ、<br>生産性を向上させることができます。</p>



<p>また、教育機関での学習用資料の作成や、<strong>自動応答システムの開発にも応用</strong>できます。</p>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import os
import csv
from google.cloud import texttospeech

# 認証情報のパスを設定
os.environ[&#39;GOOGLE_APPLICATION_CREDENTIALS&#39;] = &#39;key.json&#39;

# 音声生成関数
def generate_audio(csv_path):
    # 保存先ディレクトリをCSVファイルと同じ場所に設定
    save_directory = os.path.dirname(csv_path)
    
    # Google Cloud TTSクライアントの作成
    client = texttospeech.TextToSpeechClient()
    
    # CSVファイルの読み込み
    with open(csv_path, &#39;r&#39;, newline=&#39;&#39;, encoding=&#39;utf-8&#39;) as csvfile:
        reader = csv.reader(csvfile)
        
        # 各行のA列を順番に処理
        for index, row in enumerate(reader):
            if len(row) &gt; 0:  # A列に値があるか確認
                word = row[0]  # A列の単語を取得
                
                # テキスト入力の設定
                synthesis_input = texttospeech.SynthesisInput(text=word)
                
                # 音声の設定（en-US-Standard-J話者を使用）
                voice = texttospeech.VoiceSelectionParams(
                    language_code=&quot;en-US&quot;,
                    name=&quot;en-US-Standard-J&quot;
                )
                
                # オーディオ設定
                audio_config = texttospeech.AudioConfig(
                    audio_encoding=texttospeech.AudioEncoding.LINEAR16  # WAVフォーマット
                )
                
                # 音声合成のリクエスト
                response = client.synthesize_speech(
                    input=synthesis_input,
                    voice=voice,
                    audio_config=audio_config
                )
                
                # ファイル名をインデックスと単語で作成し、保存先パスを設定
                filename = os.path.join(save_directory, f&#39;{index+1}_{word}.wav&#39;)
                
                # 音声データの保存
                with open(filename, &#39;wb&#39;) as out:
                    out.write(response.audio_content)
                    print(f&#39;Saved: {filename}&#39;)

# メイン処理
if __name__ == &quot;__main__&quot;:
    # CSVファイルのパスを指定
    csv_path = &#39;voice.csv&#39;
    
    # ファイルが存在するか確認
    if os.path.exists(csv_path):
        generate_audio(csv_path)
        print(&quot;音声変換が完了しました。&quot;)
    else:
        print(&quot;エラー: 指定されたCSVファイルが存在しません。&quot;)</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「os」：ファイルシステムのパスや環境変数を扱うために使用されている。ここでは環境変数を設定し、CSVファイルの場所を扱うために必要。<br>「csv」：CSVファイルを読み込むために使用される。スクリプトでは、各行のA列の内容を音声生成のために取得する必要がある。<br>「google.cloud.texttospeech」：Google Cloud Text-to-Speech APIを利用するために必要。音声合成のリクエストを送るために使用されている。</p>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「csv_path」：CSVファイルのパスを保持する。音声生成対象のファイルの場所を指定するために必要。<br>「save_directory」：音声ファイルの保存先ディレクトリのパスを保持する。CSVファイルと同じ場所に音声ファイルを保存するために使用。<br>「client」：Google Cloud Text-to-Speech APIクライアントのインスタンス。音声合成を行うために必要。<br>「word」：CSVファイルのA列から読み取った単語を保持する。この単語が音声合成の対象となる。<br>「synthesis_input」：音声合成に使用するテキストを保持する。Google Cloud Text-to-Speech APIに渡すために作成される。<br>「voice」：音声の設定を保持する。使用する言語コードと話者の情報が含まれ、どの話者を使って音声を生成するか指定する。<br>「audio_config」：オーディオ出力の設定を保持する。生成する音声のフォーマット（WAV形式）を指定する。<br>「filename」：生成した音声ファイルの保存先パスを保持する。インデックスと単語を使ってファイル名を作成。</p>



<p><strong>generate_audioクラス</strong></p>



<p>「csv_path」からCSVファイルを読み込み、A列の単語に対して音声を生成する関数。Google Cloud Text-to-Speech APIを利用して、各単語を音声ファイル（WAV形式）に変換し、CSVファイルと同じディレクトリに保存する。<br>まず「save_directory」をCSVファイルのディレクトリに設定し、APIクライアント「client」を生成する。</p>



<p>次に、CSVファイルを読み込み、<strong>各行に対してA列の単語を取得</strong>する。取得した単語を「synthesis_input」として設定し、音声の設定「voice」とオーディオ出力の設定「audio_config」を指定して「synthesize_speech」メソッドを呼び出し、音声を生成する。</p>



<p>最後に、<strong>生成した音声データを「filename」に保存</strong>する。ファイル名にはインデックスと単語を使っており、保存先ディレクトリに「.wav」ファイルとして保存する。</p>



<p>本ソースコードでは、「voice.csv」と先に指定しているが、<br>Tkinterを使うことでユーザーの設定によって決めることもできる。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>TkinterのEntryについて紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-entry/" title="【Python】Tkinterエントリー作成、初期値の取得を解説" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinterエントリー作成、初期値の取得を解説</div><div class="blogcard-snippet internal-blogcard-snippet">PythonのTkinterでエントリーボックス（Entry）の解説をします。配置や文字列の取得、初期値、クリアなど基本事項を解説しながらログインフォームの制作しています。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.04.29</div></div></div></div></a>
</div>



<h2 class="wp-block-heading">実演</h2>



<p>スクリプトを実行すると、csv（voice.csv）にのA列にあるテキストを読み込み、<br>wav形式で保存します。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="683" height="333" src="https://alicia-ing.com/wp-content/uploads/2024/11/csv_data.webp" alt="csvデータ" class="wp-image-8226" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/csv_data.webp 683w, https://alicia-ing.com/wp-content/uploads/2024/11/csv_data-300x146.webp 300w" sizes="(max-width: 683px) 100vw, 683px" /></figure>



<p>wavファイルの保存先は、実行したPythonのコードと同じ断層です。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>Google Text-to-Speechは、テキストを簡単に音声に変換する強力なツールです。<br>特にPythonと組み合わせることで、柔軟に自動音声生成を行うことが可能になります。</p>



<p>本記事では、APIの取得からPythonによる実装までを詳細に解説しました。<br>業務の効率化や教育コンテンツの作成など、さまざまな用途で活用してみてください。</p>



<p>Google Text-to-Speechを使うことで、ナレーション、案内、教育用途、さらには商用プロジェクトでの音声合成など、多彩なシーンで活用することができます。</p>



<p>また、Pythonのコードを使えば、複数のテキストを自動的に音声ファイルに変換するプロセスを効率化でき、生産性を向上させることができます。</p>



<p>APIの設定や実装手順は一見複雑に思えますが、<br>本記事を参考にすれば初めての方でも問題なく取り組むことができるでしょう。</p>



<p>Google Cloudの無料枠を上手に利用し、まずは個人プロジェクトから始めてみるのも良いでしょう。音声合成の楽しさと可能性をぜひ体験してみてください。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/google-text-to-speech/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】moviepyできること｜mp3・GIF編集変換</title>
		<link>https://alicia-ing.com/programming/python/moviepy/</link>
					<comments>https://alicia-ing.com/programming/python/moviepy/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Sun, 17 Nov 2024 22:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=8067</guid>

					<description><![CDATA[PythonのライブラリであるMoviePyを使えば、動画編集が簡単に自動化できます。 面倒な手作業をスクリプトに置き換えることで効率的に編集作業を進められるこのライブラリは、動画のカットや結合、テキスト追加からGIFへ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>PythonのライブラリであるMoviePyを使えば、<br>動画編集が簡単に自動化できます。</p>



<p>面倒な手作業をスクリプトに置き換えることで<strong>効率的に編集作業を進められ</strong>るこのライブラリは、動画のカットや結合、テキスト追加からGIFへの変換まで多岐にわたる機能を提供します。</p>



<p>本記事では、MoviePyの基本的な使い方から応用的な操作までをわかりやすく解説します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>動画編集を自動化したいプログラマーやエンジニア</li>



<li>Pythonで動画編集に挑戦したい初心者</li>



<li>SNS用のショート動画やGIFを素早く作りたい方</li>



<li>自動化した動画編集パイプラインを構築したい方</li>



<li>動画編集ソフトを使わずにコードで柔軟に編集したい方</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">moviepy</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/movie.webp" alt="moviepyについて" class="wp-image-8158" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/movie.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/movie-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/movie-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/movie-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>MoviePyは、Pythonで<strong>動画や音声を編集するオープンソースライブラリ</strong>です。</p>



<p>動画のカットや結合、オーバーレイ、<br>速度変更など多くの機能を持ち、<br>mp4からGIFやmp3など他の形式への変換も簡単に行えます。</p>



<p>自動化された<strong>動画編集ワークフローを作るのに非常に役立つツール</strong>です。</p>



<h2 class="wp-block-heading">基本的な機能</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/basic-function.webp" alt="基本機能について" class="wp-image-8159" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/basic-function.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/basic-function-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/basic-function-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/basic-function-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>MoviePyを使って、基本的な動画編集を簡単に行うことができます。<br>以下に、主な機能とそれぞれのコード例を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-check"><span class="tab-caption-box-label-text block-box-label-text box-label-text">機能一覧</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>トリミング</li>



<li>結合</li>



<li>リサイズ</li>



<li>フレームレートの変更</li>
</ul>
</div></div>



<h3 class="wp-block-heading">動画のカット（トリミング）</h3>



<p>動画の特定の部分を切り取ることで、必要なシーンだけを抽出できます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;).subclip(10, 30)  # 10秒から30秒の部分を切り取る
clip.write_videofile(&quot;output_trimmed.mp4&quot;)</code></pre></div>



<p>input_video.mp4の10秒から30秒までの部分を切り取って、<br>新しい動画ファイルとして保存します。</p>



<h3 class="wp-block-heading">複数クリップの結合</h3>



<p>複数の動画を連結して1つの動画にすることも簡単です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, concatenate_videoclips

clip1 = VideoFileClip(&quot;video1.mp4&quot;).subclip(0, 10)
clip2 = VideoFileClip(&quot;video2.mp4&quot;).subclip(5, 15)

final_clip = concatenate_videoclips([clip1, clip2])
final_clip.write_videofile(&quot;output_concatenated.mp4&quot;)</code></pre></div>



<p>video1.mp4の最初の10秒間とvideo2.mp4の5秒から15秒の部分を結合して、<br>新しい動画を作成しています。</p>



<div class="wp-block-cocoon-blocks-balloon-ex-box-1 speech-wrap sb-id-2 sbs-stn sbp-l sbis-cb cf block-box not-nested-style cocoon-block-balloon"><div class="speech-person"><figure class="speech-icon"><img decoding="async" src="https://alicia-ing.com/wp-content/uploads/2023/05/cropped-alicia.webp" alt="筆者" class="speech-icon-image"/></figure><div class="speech-name">筆者</div></div><div class="speech-balloon">
<p>最近のYouTubeは、総集編が多いので、<br>これで自動編集ができる！</p>
</div></div>



<h3 class="wp-block-heading">動画のリサイズ</h3>



<p>動画の解像度を変更して、<strong>特定のサイズにリサイズ</strong>することができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;)
resized_clip = clip.resize(height=720)  # 高さを720ピクセルにリサイズ
resized_clip.write_videofile(&quot;output_resized.mp4&quot;)</code></pre></div>



<p>動画の高さを720ピクセルに変更して、新しいファイルとして保存します。</p>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">フレームレートの変更</h3>



<p>フレームレートを変更することで、<strong>スムーズさを調整</strong>したり、<strong>特殊な演出</strong>を加えることができます。<br>フレームレートとは、<strong>動画やゲームにおいて1秒間に表示される画像</strong>（フレーム）の数を示す単位です。</p>



<p>要するに、1秒の動きを表現するために30枚の画像を使うと30fpsになります。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;).set_fps(15) # フレームレートを15fpsに変更
clip.write_videofile(&quot;output_changed_fps.mp4&quot;)</code></pre></div>



<p>元の動画のフレームレートを15fpsに設定しています。</p>



<h2 class="wp-block-heading">動画・画像の加工</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/video-image.webp" alt="動画加工について" class="wp-image-8160" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/video-image.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/video-image-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/video-image-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/video-image-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>MoviePyでは、動画や画像に対してさらに多くの加工を行うことが可能です。</p>



<p>機能として備わっていますが、<br>トリミングやオーバーレイ、テキストの追加は、<br><strong>編集ソフトで動画作り</strong>した方がやりやすいです。</p>



<h3 class="wp-block-heading">クロッピング（トリミング）</h3>



<p>動画の一部を切り取ることで、<strong>不要な部分を削除</strong>し、必要な部分のみを残すことができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;)
cropped_clip = clip.crop(x1=100, y1=50, x2=400, y2=300)  # 指定したエリアをクロップ
cropped_clip.write_videofile(&quot;output_cropped.mp4&quot;)</code></pre></div>



<p>動画の特定のエリアをクロップして、新しい動画として保存します。</p>



<h3 class="wp-block-heading">画像のオーバーレイ</h3>



<p>動画の上に画像をオーバーレイすることが可能です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, ImageClip, CompositeVideoClip

video_clip = VideoFileClip(&quot;input_video.mp4&quot;)
image_clip = ImageClip(&quot;overlay_image.png&quot;).set_duration(video_clip.duration)
image_clip = image_clip.set_position((&quot;right&quot;, &quot;top&quot;))  # 画像の位置を右上に設定

composite_clip = CompositeVideoClip([video_clip, image_clip])
composite_clip.write_videofile(&quot;output_with_overlay.mp4&quot;)</code></pre></div>



<p>input_video.mp4の上にoverlay_image.pngを右上に表示させています。</p>



<h3 class="wp-block-heading">テキストの追加</h3>



<p>動画上にテキストを追加することができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip

video_clip = VideoFileClip(&quot;input_video.mp4&quot;)
text_clip = TextClip(&quot;Hello, World!&quot;, fontsize=70, color=&#39;white&#39;).set_duration(5)
text_clip = text_clip.set_position(&#39;center&#39;).fadein(1).fadeout(1)  # フェードイン・フェードアウト効果

composite_clip = CompositeVideoClip([video_clip, text_clip])
composite_clip.write_videofile(&quot;output_with_text.mp4&quot;)</code></pre></div>



<p><strong>動画の中央に5秒間表示されるテキスト</strong>を追加し、<br><strong>フェードインとフェードアウト効果</strong>を加えています。</p>



<h3 class="wp-block-heading">動画の回転</h3>



<p>動画を任意の角度に回転させることができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;)
rotated_clip = clip.rotate(90)  # 動画を90度回転
rotated_clip.write_videofile(&quot;output_rotated.mp4&quot;)</code></pre></div>



<p>動画を90度回転させています。</p>



<h2 class="wp-block-heading">動画・音声の効果</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/effect.webp" alt="動画音声の効果について" class="wp-image-8161" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/effect.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/effect-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/effect-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/effect-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>動画に視覚的な効果を加えることで、より魅力的なコンテンツを作成することができます。</p>



<p>また、音声を調整して臨場感がある動画作りができます。</p>



<h3 class="wp-block-heading">フェードイン/フェードアウト</h3>



<p><strong>フェード効果</strong>を使って、動画の始まりや終わりを滑らかに演出します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip
from moviepy.video.fx import fadein, fadeout

clip = VideoFileClip(&quot;input_video.mp4&quot;)
clip_with_fadein = fadein.fadein(clip, 2)  # 最初の2秒をフェードイン
clip_with_fadeout = fadeout.fadeout(clip_with_fadein, 2)  # 最後の2秒をフェードアウト
clip_with_fadeout.write_videofile(&quot;output_fade.mp4&quot;)</code></pre></div>



<p>最初の2秒間のフェードインと最後の2秒間のフェードアウトを加えています。</p>



<h3 class="wp-block-heading">速度変更</h3>



<p>動画の再生速度を変更することができます（<strong>スローモーションや早送り</strong>）。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, vfx

clip = VideoFileClip(&quot;input_video.mp4&quot;)
sped_up_clip = clip.fx(vfx.speedx, 2)  # 2倍速にする
sped_up_clip.write_videofile(&quot;output_sped_up.mp4&quot;)</code></pre></div>



<p>動画を2倍速にして新しいファイルとして保存しています。</p>



<h3 class="wp-block-heading">ミラーリング（反転）</h3>



<p>動画を<strong>左右または上下に反転</strong>させることが可能です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;)
mirrored_clip = clip.fx(vfx.mirror_x)  # 左右反転
mirrored_clip.write_videofile(&quot;output_mirrored.mp4&quot;)</code></pre></div>



<p>動画を左右反転させています。</p>



<h3 class="wp-block-heading">カラー調整</h3>



<p>動画の色調（輝度、コントラスト、彩度など）を調整できます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip
from moviepy.video.fx import colorx

clip = VideoFileClip(&quot;input_video.mp4&quot;)
brightened_clip = colorx.colorx(clip, 1.5)  # 輝度を1.5倍に
brightened_clip.write_videofile(&quot;output_brightened.mp4&quot;)</code></pre></div>



<p><strong>動画の輝度</strong>を1.5倍に調整しています。</p>



<h3 class="wp-block-heading">音声の追加/削除</h3>



<p>動画の音声を削除したり、<strong>新しい音声を追加</strong>することができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, AudioFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;)
audio = AudioFileClip(&quot;new_audio.mp3&quot;).set_duration(clip.duration)
clip_with_new_audio = clip.set_audio(audio)
clip_with_new_audio.write_videofile(&quot;output_with_new_audio.mp4&quot;)</code></pre></div>



<p>input_video.mp4に新しい音声ファイルnew_audio.mp3を追加しています。</p>



<h3 class="wp-block-heading">音量調整</h3>



<p>動画や音声クリップの音量を変更することができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;)
quieter_clip = clip.volumex(0.5)  # 音量を半分に
quieter_clip.write_videofile(&quot;output_quieter.mp4&quot;)</code></pre></div>



<p>動画の音量を半分にしています。</p>



<h3 class="wp-block-heading">フェードイン/フェードアウト（音声）</h3>



<p>音声クリップにフェード効果を加えることが可能です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, AudioFileClip
from moviepy.audio.fx import audio_fadein, audio_fadeout

clip = VideoFileClip(&quot;input_video.mp4&quot;)
audio = clip.audio
faded_audio = audio_fadein.audio_fadein(audio, 2).fx(audio_fadeout.audio_fadeout, 2)
clip_with_faded_audio = clip.set_audio(faded_audio)
clip_with_faded_audio.write_videofile(&quot;output_faded_audio.mp4&quot;)</code></pre></div>



<p>音声に最初と最後の2秒間のフェードイン・フェードアウト効果を追加しています。</p>



<h2 class="wp-block-heading">応用例</h2>



<p>MoviePyを使って、さらに複雑な動画編集を行うことも可能です。<br>以下にいくつかの応用例を紹介します。</p>



<h3 class="wp-block-heading">動画に画像をオーバーレイ</h3>



<p>動画の上にロゴや他の画像を追加することで、カスタマイズされた動画を作成することができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>from moviepy.editor import VideoFileClip, ImageClip, CompositeVideoClip

video_clip = VideoFileClip(&quot;input_video.mp4&quot;)
image_clip = ImageClip(&quot;overlay_image.png&quot;).set_duration(video_clip.duration)
image_clip = image_clip.set_position((&quot;right&quot;, &quot;top&quot;))  # 画像の位置を右上に設定

composite_clip = CompositeVideoClip([video_clip, image_clip])
composite_clip.write_videofile(&quot;output_with_overlay.mp4&quot;)</code></pre></div>



<p>この例では、input_video.mp4の上にoverlay_image.pngを右上に表示させています。</p>



<h3 class="wp-block-heading">テキストのアニメーション</h3>



<p>動画上にアニメーション化されたテキストを追加して、より魅力的な演出を行います。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip

video_clip = VideoFileClip(&quot;input_video.mp4&quot;)
text_clip = TextClip(&quot;Hello, World!&quot;, fontsize=70, color=&#39;white&#39;).set_duration(5)
text_clip = text_clip.set_position(&#39;center&#39;).fadein(1).fadeout(1)  # フェードイン・フェードアウト効果

composite_clip = CompositeVideoClip([video_clip, text_clip])
composite_clip.write_videofile(&quot;output_with_text.mp4&quot;)</code></pre></div>



<p>このコードでは、動画の中央に5秒間表示されるテキストを追加し、<br>フェードインとフェードアウト効果を加えています。</p>



<h3 class="wp-block-heading">ピクチャー・イン・ピクチャー（PIP）効果</h3>



<p>メインの動画の中に別の小さな動画を配置することで、<br>ピクチャー・イン・ピクチャー効果を実現します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip, CompositeVideoClip

main_clip = VideoFileClip(&quot;main_video.mp4&quot;)
small_clip = VideoFileClip(&quot;small_video.mp4&quot;).resize(height=150).set_position((10, 10)).set_duration(main_clip.duration)

pip_clip = CompositeVideoClip([main_clip, small_clip])
pip_clip.write_videofile(&quot;output_pip.mp4&quot;)</code></pre></div>



<p>main_video.mp4の左上に小さなsmall_video.mp4を配置しています。</p>



<h2 class="wp-block-heading">形式変換</h2>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/transformation.webp" alt="形式を変えるには" class="wp-image-8162" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/transformation.webp 1200w, https://alicia-ing.com/wp-content/uploads/2024/11/transformation-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/11/transformation-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/11/transformation-768x403.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p>MoviePyは動画のフォーマット変換もサポートしています。</p>



<p>MoviePyは多機能ですが、<strong>直感で編集できない</strong>ので、用途が限られます。<br>しかし、動画を結合して、それをmp3やGIFに変換することで、<br>色々な場所で使うことができます。</p>



<p>例えば、<strong>私の場合は動画をGIFに変換してブログ投稿</strong>したり、<br>逆にGIFをmp4に変換して動画編集したりしています。</p>



<p>このように、フォーマットの変換はかなり使いやすいです。</p>



<h3 class="wp-block-heading">mp3への変換</h3>



<p>動画から音声を抽出してmp3ファイルとして保存できます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;)
clip.audio.write_audiofile(&quot;output_audio.mp3&quot;)</code></pre></div>



<p>input_video.mp4の<strong>音声部分を抽出</strong>して、output_audio.mp3として保存します。</p>



<h3 class="wp-block-heading">GIFへの変換</h3>



<p>特定のシーンをGIFとしてエクスポートすることで、短いアニメーションを簡単に作成できます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

clip = VideoFileClip(&quot;input_video.mp4&quot;).subclip(0, 5)  # 最初の5秒をGIFに変換
clip.write_gif(&quot;output.gif&quot;)</code></pre></div>



<p>動画の最初の5秒間を<strong>GIFとしてエクスポート</strong>しています。</p>



<h3 class="wp-block-heading">GIFをmp4に変換</h3>



<p>GIFをインポートして、output.mp4をエクスポートしています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from moviepy.editor import VideoFileClip

# GIFをmp4に変換
clip = VideoFileClip(&quot;input.gif&quot;)  # 入力GIFファイルを指定
clip.write_videofile(&quot;output.mp4&quot;, codec=&quot;libx264&quot;)  # mp4形式で出力</code></pre></div>



<h2 class="wp-block-heading">まとめ</h2>



<p>MoviePyを使えば、Pythonで動画や音声を自由自在に編集することができます。</p>



<p>動画のカット、結合、リサイズ、エフェクト追加など、<br>MoviePyの基本機能を使いこなすことで、柔軟にコンテンツを作成することが可能です。</p>



<p>また、GIFやmp3などの形式に変換することも容易で、SNS用の素材作りにも最適です。</p>



<p>応用的な操作として、画像やテキストのオーバーレイ、ピクチャー・イン・ピクチャー効果などを利用することで、より高度で魅力的な動画編集が可能になります。</p>



<p>ぜひ本記事を参考に、MoviePyで様々な動画編集に挑戦してみてください！</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/moviepy/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】cmakeを使った顔のランドマーク検出システム</title>
		<link>https://alicia-ing.com/programming/python/cmake-face-landmark/</link>
					<comments>https://alicia-ing.com/programming/python/cmake-face-landmark/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Wed, 16 Oct 2024 22:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=7302</guid>

					<description><![CDATA[Pythonで顔認識システムを作りたいと考えているけど、どこから始めればいいか迷っている方も多いのではないでしょうか。 本記事では、CMakeとPythonを組み合わせて顔認証システムをゼロから作成する手順を解説します。 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<p>顔にランドマーク（3Dマスク）を付ける。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1024" height="512" src="https://alicia-ing.com/wp-content/uploads/2024/10/complete-1.webp" alt="顔のランドマーク検出" class="wp-image-7303" srcset="https://alicia-ing.com/wp-content/uploads/2024/10/complete-1.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/10/complete-1-300x150.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/10/complete-1-768x384.webp 768w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>※画像の人物は、<a target="_self" href="https://www.photo-ac.com/main/genface">こちら</a>からお借りしました。</p>
</div></div>



<p>Pythonで顔認識システムを作りたいと考えているけど、<br>どこから始めればいいか迷っている方も多いのではないでしょうか。</p>



<p>本記事では、CMakeとPythonを組み合わせて顔認証システムをゼロから作成する手順を解説します。<br>Pythonの強力なライブラリとCMakeのビルド自動化の力を駆使して、<br>実用的で高性能な顔認証システムを構築します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>顔認識システムをPythonで作成したい方</li>



<li>CMakeの基本を学び、プロジェクトに活用したい方</li>



<li>OpenCVやface_recognitionライブラリを使った応用技術を学びたい方</li>



<li>画像処理や機械学習に興味がある初級～中級者</li>



<li>高度な顔認識アルゴリズムを効率的に導入したい方</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">cmakeとは</h2>



<p>CMakeは、クロスプラットフォームのビルドシステムで、<br>ソースコードのコンパイルやビルドの自動化を行うツールです。</p>



<p>複雑なプロジェクトのビルドプロセスを簡潔にまとめて、環境に依存せずにコードを管理できる点で、<br>特に多くのライブラリを利用する<strong>C++プロジェクト</strong>やPython拡張モジュール開発において広く利用されています。</p>



<h3 class="wp-block-heading">用途</h3>



<p>CMakeは、主にC++プロジェクトで利用されますが、<br>Python拡張やライブラリのビルドにも非常に便利です。</p>



<p>顔認証システムのように、OpenCVやface_recognitionなどの外部ライブラリを統合するプロジェクトにおいて、CMakeを使うと環境に依存せず簡単にセットアップが可能です。</p>



<h3 class="wp-block-heading">インストール方法</h3>



<p>Python専用のライブラリを使う場合は、pipでインストールできますが、<br>cmakeはpipではなく、公式のウェブサイトからダウンロードします。</p>



<p></p>



<h2 class="wp-block-heading">顔ランドマーク（3Dマスク）の検出</h2>



<p>顔認識のさらなるステップとして、顔のランドマーク検出が重要です。</p>



<p>顔のランドマークとは、目、眉毛、鼻、口などの主要なパーツの位置を指します。</p>



<p>これにより、顔の特徴を捉えた3Dマスク風の画像処理が可能になります。<br>Pythonのface_recognitionライブラリを使うと、これらのランドマークを簡単に検出できます。</p>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import cv2
import face_recognition
import numpy as np
from tkinter import filedialog
import os

# 画像ファイルを選択
def select_image():
    global image_path
    image_path = filedialog.askopenfilename(title=&quot;画像を選択&quot;, filetypes=[(&quot;Image files&quot;, &quot;*.jpg;*.png&quot;)])
    if image_path:
        apply_3d_mask(image_path)

# 画像に3Dマスク風の線を付けて新しい画像として保存
def apply_3d_mask(image_path):
    image = cv2.imread(image_path)
    if image is None:
        print(&quot;画像の読み込みに失敗しました。&quot;)
        return
    
    # 顔のランドマークを検出
    face_landmarks_list = face_recognition.face_landmarks(image)
    
    if len(face_landmarks_list) == 0:
        print(&quot;顔が検出されませんでした。&quot;)
        return
    
    # 各顔パーツに線を描画
    for face_landmarks in face_landmarks_list:
        # 顎の輪郭に沿って線を描く
        cv2.polylines(image, [np.array(face_landmarks[&#39;chin&#39;])], isClosed=False, color=(0, 255, 0), thickness=2)
        
        # 眉毛
        cv2.polylines(image, [np.array(face_landmarks[&#39;left_eyebrow&#39;])], isClosed=False, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks[&#39;right_eyebrow&#39;])], isClosed=False, color=(0, 255, 0), thickness=2)
        
        # 鼻
        cv2.polylines(image, [np.array(face_landmarks[&#39;nose_bridge&#39;])], isClosed=False, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks[&#39;nose_tip&#39;])], isClosed=False, color=(0, 255, 0), thickness=2)
        
        # 目
        cv2.polylines(image, [np.array(face_landmarks[&#39;left_eye&#39;])], isClosed=True, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks[&#39;right_eye&#39;])], isClosed=True, color=(0, 255, 0), thickness=2)
        
        # 口
        cv2.polylines(image, [np.array(face_landmarks[&#39;top_lip&#39;])], isClosed=True, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks[&#39;bottom_lip&#39;])], isClosed=True, color=(0, 255, 0), thickness=2)
    
    # 新しいファイルとして保存
    save_path = os.path.join(os.path.dirname(image_path), f&quot;3d_mask_{os.path.basename(image_path)}&quot;)
    cv2.imwrite(save_path, image)
    print(f&quot;3Dマスク画像が保存されました: {save_path}&quot;)

select_image()</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「cv2」：OpenCVを使用して画像の読み込み、処理、保存を行うために使用。画像にランドマークを描画する際にも利用される。<br>「face_recognition」：顔のランドマーク（顎、眉毛、目、鼻、口など）を検出するために使用。<br>「numpy」：顔のランドマークの座標を配列に変換し、cv2.polylinesで使用するために利用。<br>「tkinter.filedialog」：ファイル選択ダイアログを使用して、画像ファイルを選択するために使用。<br>「os」：ファイルのパスを操作し、新しいファイルの保存先や名前を設定するために使用。</p>



<p>「cv2」と「face_recognition」、「numpy」はpipでインストールする必要があります。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>pip install opencv-python  
pip install face_recognition  
pip install numpy  </code></pre></div>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「image_path」：ユーザーが選択した画像のファイルパスを保存する変数。<br>select_image()関数で取得され、apply_3d_mask()関数で使用される。</p>



<ul class="wp-block-list">
<li><strong>select_image関数</strong></li>
</ul>



<p>ユーザーがファイル選択ダイアログを使用して画像ファイルを選択する</p>



<p>filedialog.askopenfilename()を用いて<strong>画像ファイルパスを取得</strong>し、<br>選択された画像が存在する場合にapply_3d_mask()関数を呼び出す。</p>



<ul class="wp-block-list">
<li><strong>apply_3d_mask関数</strong></li>
</ul>



<p>画像を読み込みface_recognition.face_landmarks()を使用して、<br><strong>顔のランドマーク</strong>（顎、眉毛、鼻、目、口）を検出する。</p>



<p>各ランドマークに基づいて、<br><strong>cv2.polylines()で緑色の線を描画</strong>する（例：顎の輪郭や眉毛に沿った線）。</p>



<p>最後に、新しい画像として処理された画像を<strong>元のディレクトリに保存</strong>し、<br>保存先をコンソールに表示する。</p>



<h2 class="wp-block-heading">実演</h2>



<p>本スクリプトは、まずユーザーがファイル選択ダイアログを通じて画像を選び、<br>OpenCVを使用して画像を読み込みます。</p>



<p>その後、face_recognitionライブラリを使って顔のランドマーク（目、鼻、口など）を検出し、<br>各ランドマークに沿って線を描画します。</p>



<p>最終的に新しい画像として保存します。<br>ランドマーク検出は、リアルタイム顔認識や表情分析など、さまざまな応用に使われます。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>本記事では、CMakeを使ったPythonの顔認証システム構築の基礎から実践までを紹介しました。</p>



<p>CMakeを使ってプロジェクトを効率的に管理し、OpenCVやface_recognitionを活用することで、<br>実用的な顔認証システムを短期間で開発する方法が理解できたでしょう。</p>



<p>PythonとCMakeの組み合わせは、今後ますます重要なスキルとなるでしょう。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/cmake-face-landmark/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】Tkinterスライダーバーの使い方、グラフ操作</title>
		<link>https://alicia-ing.com/programming/python/tkinter-slider/</link>
					<comments>https://alicia-ing.com/programming/python/tkinter-slider/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Wed, 25 Sep 2024 17:14:43 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=7044</guid>

					<description><![CDATA[PythonでGUI（グラフィカルユーザーインターフェース）を作成するとき、Tkinterは非常に便利なライブラリです。 スライダーバーは、ユーザーがリアルタイムで数値を操作できて、matplotlibを使えば、グラフな [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="950" src="https://alicia-ing.com/wp-content/uploads/2024/09/complete-3.gif" alt="" class="wp-image-7058"/></figure>
</div></div>



<p>PythonでGUI（グラフィカルユーザーインターフェース）を作成するとき、Tkinterは非常に便利なライブラリです。</p>



<p>スライダーバーは、<strong>ユーザーがリアルタイムで数値を操作</strong>できて、<strong>matplotlib</strong>を使えば、グラフなどを動的に変化させることが可能です。</p>



<p>本記事では、Tkinterを使ってスライダーバーを作成し、<br>さらにそのスライダーでリアルタイムにグラフを操作する方法について解説します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>PythonでのGUI開発に興味がある方</li>



<li>Tkinterを使ってみたい初学者</li>



<li>動的なグラフ操作を実装してみたい方</li>



<li>数学的な関数を可視化するツールを作成したい方</li>



<li>Pythonのプロジェクトでユーザーインターフェースを改善したい方</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">画面（ウィンドウ）作成</h2>



<p>Tkinterを使って、まずは画面（ウィンドウ）を作成します。<br>これはTkinterの基本的な使い方であり、すべての<strong>GUIアプリケーションの出発点</strong>です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

# Tkinterウィンドウの作成
root = tk.Tk()
root.title(&quot;Tkinterウィンドウの作成&quot;)

# ウィンドウサイズ設定
root.geometry(&quot;400x300&quot;)

# メインループ
root.mainloop()</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="390" src="https://alicia-ing.com/wp-content/uploads/2024/09/window-1-1024x390.webp" alt="" class="wp-image-7059" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/window-1-1024x390.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/window-1-300x114.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/window-1-768x293.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/window-1.webp 1089w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>tk.Tk()メソッドでアプリケーションウィンドウを生成し、<br>その後、ウィジェット（ボタンやラベルなど）を配置していきます。</p>



<h2 class="wp-block-heading">スライダーバーの作成</h2>



<p>TkinterのScaleウィジェットを使って、スライダーバーを簡単に作成できます。<br><strong>スライダーは数値の範囲を設定</strong>し、その範囲内でユーザーが値を選べるようにするUI要素です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

# Tkinterウィンドウの作成
root = tk.Tk()
root.title(&quot;スライダーバーの作成&quot;)

# スライダーバーの作成
slider = tk.Scale(root)
slider.pack(padx=20, pady=20)

# メインループ
root.mainloop()
</code></pre></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="929" height="431" src="https://alicia-ing.com/wp-content/uploads/2024/09/Slider.webp" alt="" class="wp-image-7060" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/Slider.webp 929w, https://alicia-ing.com/wp-content/uploads/2024/09/Slider-300x139.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/Slider-768x356.webp 768w" sizes="(max-width: 929px) 100vw, 929px" /></figure>



<p>スライダーバーは、<strong>数値を自由に操作できる</strong>ため多くの用途で役立ちます。<br>具体的には、以下のようなシーンで利用できます。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-graduation-cap"><span class="tab-caption-box-label-text block-box-label-text box-label-text">スライダーバーの用途</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>ユーザーがリアルタイムで数値を調整できる場面（例えば音量調整や色の選択）</li>



<li>ゲームやシミュレーションのパラメータを操作</li>



<li>数学的な関数やグラフの動的可視化</li>



<li>画像処理アプリケーションでのフィルター強度の調整</li>



<li>アニメーションやモデルの速度・位置調整</li>
</ul>
</div></div>



<h2 class="wp-block-heading">初期値の設定</h2>



<p>スライダーバーには初期値を設定できます。<br>これにより、<strong>アプリケーションが起動した時点</strong>で、あらかじめ選択された状態が表示されます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

# Tkinterウィンドウの作成
root = tk.Tk()
root.title(&quot;初期値の設定&quot;)

# スライダーバーの作成
slider = tk.Scale(root, from_=0, to=100, orient=tk.HORIZONTAL, label=&quot;スライダー&quot;)
slider.set(50)  # 初期値を50に設定
slider.pack(padx=20, pady=20)

# メインループ
root.mainloop()
</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="538" src="https://alicia-ing.com/wp-content/uploads/2024/09/set-1024x538.webp" alt="" class="wp-image-7061" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/set-1024x538.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/set-300x158.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/set-768x403.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/set.webp 1030w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>set()メソッドを使い、スライダーバーの初期値を設定を行います。</p>



<h2 class="wp-block-heading">オプション一覧（色・フォント・大きさ変更・デザインなど）</h2>



<p>Tkinterでは、スライダーバーのデザインや外観をカスタマイズすることが可能です。<br>以下のオプションを用いることで、<strong>スライダーを自由に設定</strong>できます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

# Tkinterウィンドウの作成
root = tk.Tk()
root.title(&quot;スライダーのオプション&quot;)

# スライダーバーの作成（デザイン変更）
slider = tk.Scale(root, from_=0, to=100, orient=tk.HORIZONTAL, label=&quot;スライダー&quot;, length=300, width=20, font=(&quot;Helvetica&quot;, 14), fg=&quot;blue&quot;, bg=&quot;lightgray&quot;)
slider.pack(padx=20, pady=20)

# メインループ
root.mainloop()
</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="374" src="https://alicia-ing.com/wp-content/uploads/2024/09/option-1-1024x374.webp" alt="" class="wp-image-7062" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/option-1-1024x374.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/option-1-300x110.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/option-1-768x281.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/option-1.webp 1359w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-graduation-cap"><span class="tab-caption-box-label-text block-box-label-text box-label-text">オプション一覧</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>color：スライダーバー自体や関連する要素の色を変更。RGB値をスライダーで動的に変えることで、リアルタイムでグラフの色を変更することが可能。</li>



<li>font：ラベルやタイトルに使うフォントのスタイルやサイズを設定可能。</li>



<li>width：スライダーバーの幅を設定。視認性を向上させたい場合やデザインに応じて調整。</li>



<li>length：スライダーバーの長さを設定。GUIの見た目やユーザーエクスペリエンスに合わせたカスタマイズができる。</li>



<li>orient：スライダーの方向をHORIZONTALまたはVERTICALで設定。用途に応じて使い分ける。</li>
</ul>
</div></div>



<h2 class="wp-block-heading">matplotlibグラフをスライダーで操作する</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/graph-1-1024x528.webp" alt="" class="wp-image-7064" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/graph-1-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/graph-1-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/graph-1-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/graph-1-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/graph-1.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>スライダーとグラフ描画の相性は高く</strong>、リアルタイムで関数が変化し、<br>概形の色を変えるスライダーを作成します。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>x軸（定義域）を変化させるグラフ作成を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-graph/" title="【Python】グラフ操作｜x軸の範囲を対応させるgui" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/04/tkinter-graph-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/04/tkinter-graph-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/04/tkinter-graph-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/04/tkinter-graph-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】グラフ操作｜x軸の範囲を対応させるgui</div><div class="blogcard-snippet internal-blogcard-snippet">統計学や実験で得た数値を分析するときにグラフを作成します。表計算ソフト以外にPythonでは、実測値とそれをグラフ化するライブラリがあります。ユーザーが範囲を指定してその区間のプロット結果を出力するTkinterアプリを作成します。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.08.11</div></div></div></div></a>
</div>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk
from tkinter import ttk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# グラフの更新関数
def update_graph():
    a = a_slider.get()
    b = b_slider.get()
    c = c_slider.get()
    
    # RGB色の計算
    red = color_slider.get()
    color = f&quot;#{red:02x}00ff&quot;  #赤の成分

    x = np.linspace(-10, 10, 400)
    y = a * x**2 + b * x + c
    
    ax.clear()
    ax.plot(x, y, color=color)  # 色をスライダーで変更
    ax.set_title(f&quot;y = {a}x^2 + {b}x + {c}&quot;)
    ax.set_xlabel(&quot;x&quot;)
    ax.set_ylabel(&quot;y&quot;)
    ax.grid()
    canvas.draw()

# Tkinterウィンドウ
root = tk.Tk()
root.title(&quot;二次関数グラフ&quot;)


fn=tk.Label(text=&quot;y=ax^2+bx+c&quot;)
fn.pack()


# スライダー用のフレームを作成
slider_frame = tk.Frame(root)
slider_frame.pack(pady=10)  #

# スライダーの作成
a_slider = tk.Scale(slider_frame, from_=-10, to=10, resolution=0.1, orient=tk.HORIZONTAL, command=lambda x: update_graph(),width=40)
a_slider.set(0)  # 初期値
a_slider.pack(side=tk.LEFT, padx=5)  # 横並びに配置

b_slider = tk.Scale(slider_frame, from_=-10, to=10, resolution=0.1, orient=tk.HORIZONTAL, command=lambda x: update_graph(),width=40)
b_slider.set(0)  # 初期値
b_slider.pack(side=tk.LEFT, padx=5)  # 横並びに配置

c_slider = tk.Scale(slider_frame, from_=-10, to=10, resolution=0.1, orient=tk.HORIZONTAL, command=lambda x: update_graph(),width=40)
c_slider.set(0)  # 初期値
c_slider.pack(side=tk.LEFT, padx=5)  # 横並びに配置

# 垂直スライダー (グラフの色変更)
color_slider = tk.Scale(root, from_=0, to=255, orient=tk.VERTICAL, command=lambda x: update_graph(),width=20, length=400)
color_slider.set(0)  # 初期値
color_slider.pack(side=tk.LEFT, padx=5)
tk.Label(root, text=&quot;グラフの色&quot;).pack(side=tk.LEFT)

# グラフ描画エリアの作成
fig, ax = plt.subplots()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()

update_graph()  # 初期表示

root.mainloop()</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「ttk」：tkinterの一部で、よりモダンなウィジェットスタイルを提供するために使用。<br>「numpy」：数値計算のためのライブラリ。np.linspaceを使用してグラフのx軸のデータを生成するために使用。<br>「matplotlib」：グラフ描画ライブラリ。<strong>FigureCanvasTkAggと連携</strong>して、Tkinter上でグラフを表示するために使用。</p>



<p>インストールには、それぞれ<strong>pipを使用</strong>します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>pip install numpy
pip install matplotlib</code></pre></div>



<p>数値解析には、様々なライブラリがあります。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>統計処理・データ分析で必要なライブラリをまとめています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/statpy-library/" title="【Python】 統計処理・データ分析で必要なライブラリ一覧" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/05/statpy-library-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/statpy-library-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/05/statpy-library-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/05/statpy-library-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】 統計処理・データ分析で必要なライブラリ一覧</div><div class="blogcard-snippet internal-blogcard-snippet">Pythonの統計処理で使うライブラリ「Numpy・Matplotlib・Pandas・Scipy」を紹介。さらにGoogle Colaboratoryでの処理も解説。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2024.10.27</div></div></div></div></a>
</div>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「a_slider」：二次関数の係数 a を調整するための水平スライダー。<br>「b_slider」：二次関数の係数 b を調整するための水平スライダー。<br>「c_slider」：二次関数の係数 c を調整するための水平スライダー。<br>「color_slider」：グラフの色（RGBの赤成分）を調整するための垂直スライダー。<br>「fig」：matplotlibのFigureオブジェクト。グラフ描画領域のベースとなる。<br>「ax」：matplotlibのAxesオブジェクト。グラフの描画や設定を行うための領域。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Tkinterでラベルの使い方を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-label/" title="【Python】TkinterのLabel（ラベル）使い方" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】TkinterのLabel（ラベル）使い方</div><div class="blogcard-snippet internal-blogcard-snippet">Tkinterのラベルの使い方について紹介。配置はpack()、grid()、place()３つの他、sideオプションやanchorオプションを紹介。文字の幅・高さや文字色・背景色の指定やフォントやサイズ、太さの変更も解説。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.08.11</div></div></div></div></a>
</div>



<ul class="wp-block-list">
<li><strong>関数・メソッド</strong></li>
</ul>



<p>update_graph 関数<br>スライダーの値に基づいて二次関数 y = ax^2 + bx + c を描画する。以下の処理を行います。</p>



<ul class="wp-block-list">
<li>スライダーの値（a, b, c）を取得し、それに基づいてグラフを更新。</li>



<li>x軸の値をnumpy.linspaceで生成し、y軸の値を二次関数で計算。</li>



<li>スライダーから得た色の値を使用し、グラフの線の色を変更。</li>



<li>matplotlibのaxをクリアして新しいグラフを描画。</li>



<li>canvas.drawでTkinterウィジェット上に新しいグラフを表示。</li>
</ul>



<h2 class="wp-block-heading">実演</h2>



<p>スクリプトの主要な機能は、<strong>スライダーバーを使って二次関数のグラフを操作</strong>し、<br>またグラフの色をリアルタイムで変更する点です。</p>



<ul class="wp-block-list">
<li>ウィンドウ作成：tk.Tk()でウィンドウを生成し、基本的なレイアウトを設定します。</li>



<li>スライダーの生成：a_slider、b_slider、c_sliderという3つのスライダーを作成し、これらはそれぞれ二次関数の係数 a、b、cを操作します。また、<strong>color_sliderはグラフの色（RGBの赤成分）を動的に変更</strong>します。</li>



<li>グラフの描画：<strong>matplotlib</strong>を使ってグラフを表示し、スライダーの値に基づいてグラフの形状が変わります。update_graph()関数はスライダーが操作されるたびに呼び出され、<strong>グラフがリアルタイムで再描画</strong>されます。</li>



<li>リアルタイム更新：スライダーの値を取得し、二次関数の式に適用。さらに色もRGB値に基づいて動的に変化します。<strong>ax.clear()でグラフをクリア</strong>し、新しい値に基づいたグラフが描画されます。</li>
</ul>



<h2 class="wp-block-heading">まとめ</h2>



<p>スライダーを使ったリアルタイムグラフ操作や色の動的変更などを通して、<br>Pythonでのアプリケーション開発の幅が広がります。<br>今回の例を応用すれば、データビジュアライゼーションに優れた数学ツールなどに応用が可能です。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/tkinter-slider/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】Tkinterリストボックスの使い方、値取得</title>
		<link>https://alicia-ing.com/programming/python/tkinter-list-box/</link>
					<comments>https://alicia-ing.com/programming/python/tkinter-list-box/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Mon, 23 Sep 2024 08:03:50 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=7029</guid>

					<description><![CDATA[Tkinterは、PythonでGUIアプリケーションを作成するための標準ライブラリで、リストボックス（List box）は複数のデータをユーザーに表示し、選択させるための便利なウィジェットです。 本記事では、リストボッ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="944" src="https://alicia-ing.com/wp-content/uploads/2024/09/complete-2.gif" alt="" class="wp-image-7040"/></figure>
</div></div>



<p>Tkinterは、PythonでGUIアプリケーションを作成するための標準ライブラリで、<strong>リストボックス（List box）</strong>は複数のデータをユーザーに表示し、選択させるための便利なウィジェットです。</p>



<p>本記事では、リストボックスの基本的な使い方から値の取得、削除、選択、スクロールバーの追加など応用までを詳しく解説していきます。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>Pythonで簡単なGUIアプリケーションを作りたい方</li>



<li>Tkinterのリストボックスを使ってデータを表示・操作したい方</li>



<li>ユーザー入力に応じて、表示項目を動的に変更したい方</li>



<li>スクロール可能なリストボックスを実装したい方</li>



<li>Tkinterウィジェットのデザインやオプションについて理解を深めたい方</li>
</ul>
</div></div>



<h2 class="wp-block-heading">画面（ウィンドウ）の作成</h2>



<p>リストボックスを表示するために画面（ウィンドウ）を作成します。</p>



<p>Tkinterでは、Tk()クラスを用いてメインウィンドウを作成し、そのウィンドウの中にウィジェットを配置していきます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

root = tk.Tk() 
root.title(&quot;リストボックス&quot;)  
root.geometry(&quot;200x150&quot;)  
root.mainloop()</code></pre></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="935" height="390" src="https://alicia-ing.com/wp-content/uploads/2024/09/window.webp" alt="" class="wp-image-7034" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/window.webp 935w, https://alicia-ing.com/wp-content/uploads/2024/09/window-300x125.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/window-768x320.webp 768w" sizes="(max-width: 935px) 100vw, 935px" /></figure>



<h2 class="wp-block-heading">リストボックスの作成</h2>



<p>リストボックスは、<strong>Listboxクラス</strong>を使って作成します。</p>



<p>ユーザーが複数の項目から選択できるウィジェットで、ファイル選択やオプションの選択画面などに幅広く使われます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>listbox = tk.Listbox(root, width=40, height=10)
listbox.pack()</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="389" src="https://alicia-ing.com/wp-content/uploads/2024/09/list-box-1024x389.webp" alt="" class="wp-image-7035" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/list-box-1024x389.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/list-box-300x114.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/list-box-768x292.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/list-box.webp 1184w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>リストボックスを作成し、ウィンドウに配置するためにpack()メソッドを呼び出しています。<br>その他にも、<strong>grid()メソッドやplace()メソッド</strong>などがあります。</p>



<p>リストボックスは、次のような用途に適しています。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-graduation-cap"><span class="tab-caption-box-label-text block-box-label-text box-label-text">リストボックスの用途</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>複数項目の選択肢を表示し、ユーザーに選択させる</li>



<li>ファイルやフォルダのリスト表示</li>



<li>選択項目に応じた動的な操作の実行</li>



<li>データの整理やフィルタリング操作</li>
</ul>
</div></div>



<h3 class="wp-block-heading">値を取得、選択、削除</h3>



<p>リストボックスから値を取得したり、項目を削除・選択することもできます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>#値の取得
selected_item = listbox.get(listbox.curselection())

#選択操作
listbox.select_set(0)  # 最初の項目を選択

#項目の削除
listbox.delete(0, tk.END)</code></pre></div>



<p>リスト項目を用意して、これらをリストボックスに入れれば、追加できます。<br>また、項目を初期で選択しています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

root = tk.Tk() 
root.title(&quot;リストボックス&quot;)  
root.geometry(&quot;200x150&quot;)  

listbox = tk.Listbox(root, width=40, height=10)
listbox.pack()

# リストボックスに項目を追加
items = [&quot;Apple&quot;, &quot;バナナ&quot;, &quot;葡萄&quot;, &quot;いちご&quot;]
for item in items:
    listbox.insert(tk.END, item)

# 項目を選択
listbox.select_set(0)

root.mainloop()</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="408" src="https://alicia-ing.com/wp-content/uploads/2024/09/insert-list-1024x408.webp" alt="" class="wp-image-7036" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/insert-list-1024x408.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/insert-list-300x120.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/insert-list-768x306.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/insert-list.webp 1202w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h3 class="wp-block-heading">スクロールバーの追加</h3>



<p>リストボックス（listbox）の項目が多い場合、<strong>スクロールバーを追加することでユーザーが快適に操作</strong>できるようになります。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code># リストボックスとスクロールバーの作成
listbox = tk.Listbox(root, width=40, height=10)
listbox.pack(side=tk.LEFT, fill=tk.BOTH)

scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# スクロールバーとリストボックスを連携
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)</code></pre></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="944" src="https://alicia-ing.com/wp-content/uploads/2024/09/scroll-bar.gif" alt="" class="wp-image-7037"/></figure>



<p>これにより、リストボックスに縦方向のスクロールバーが連動し、リスト内の項目がスクロール可能になります。<br><strong>リストボックスの枠が項目よりも多くなると、スクロールバーは解除</strong>されます。</p>



<h2 class="wp-block-heading">オプション一覧（色・フォント・大きさ変更・デザインなど）</h2>



<p>リストボックスもボタンやラベルのようにさまざまなオプションを設定できます。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-graduation-cap"><span class="tab-caption-box-label-text block-box-label-text box-label-text">例にしているオプション一覧</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>背景色：bg=&#8221;lightblue&#8221;のように指定して、リストボックスの背景色を変更できます。</li>



<li>フォント：font=(&#8220;Arial&#8221;, 12)でフォントスタイルとサイズを指定可能です。</li>



<li>サイズ変更：widthやheightオプションを使ってリストボックスの大きさを自由に変更できます。</li>



<li>選択項目の色：selectbackground、selectforegroundで、選択された項目の背景色を変更できます。</li>
</ul>
</div></div>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code># リストボックスのオプション設定
listbox = tk.Listbox(root, width=40, height=10, bg=&quot;lightblue&quot;, font=(&quot;Arial&quot;, 12), selectbackground=&quot;yellow&quot;,selectforeground=&quot;red&quot;)
listbox.pack()</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="445" src="https://alicia-ing.com/wp-content/uploads/2024/09/option-1024x445.webp" alt="" class="wp-image-7038" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/option-1024x445.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/option-300x130.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/option-768x334.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/option.webp 1252w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">エントリーの文字列をリストに追加する</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/add-list-1024x528.webp" alt="" class="wp-image-7039" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/add-list-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/add-list-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/add-list-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/add-list-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/add-list.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>エントリーボックスにユーザーが文字を入力し、<br><strong>ボタン、Enterキーを押すとリストボックスに追加</strong>していきます。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Tkinterのエントリーボックスの使い方を紹介します。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-entry/" title="【Python】Tkinterエントリー作成、初期値の取得を解説" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/09/tkinter-entry-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinterエントリー作成、初期値の取得を解説</div><div class="blogcard-snippet internal-blogcard-snippet">PythonのTkinterでエントリーボックス（Entry）の解説をします。配置や文字列の取得、初期値、クリアなど基本事項を解説しながらログインフォームの制作しています。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.04.29</div></div></div></div></a>
</div>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Tkinterのボタンの使い方を紹介します。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-button/" title="【Python】Tkinterボタン(Button)の作成" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinterボタン(Button)の作成</div><div class="blogcard-snippet internal-blogcard-snippet">PythonのTkinterでGUIボタンを構築する方法を紹介します。標準ボタンを作成したり配置したり、さらに色を指定して背景や文字を変更することも簡単にできます。Tkinterでアプリをつくるときには、ボタンは必須です。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.03.11</div></div></div></div></a>
</div>



<p>また、リストボックスにスクロールバーを追加して、<strong>リストをダブルクリック</strong>すると、<br>ラベルにリストの文字を追加します。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Tkinterのスライダーバーの使い方を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-slider/" title="【Python】Tkinterスライダーバーの使い方、グラフ操作" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2024/09/Slider-Bar-tk-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/Slider-Bar-tk-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/09/Slider-Bar-tk-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/09/Slider-Bar-tk-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinterスライダーバーの使い方、グラフ操作</div><div class="blogcard-snippet internal-blogcard-snippet">Tkinterでスライダーバーを使ったグラフ操作方法を解説。スライダーでリアルタイムに関数の形や色を変更できるインタラクティブなPythonアプリケーションを作成しています。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.04.29</div></div></div></div></a>
</div>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Tkinterのラベルの使い方を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-label/" title="【Python】TkinterのLabel（ラベル）使い方" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】TkinterのLabel（ラベル）使い方</div><div class="blogcard-snippet internal-blogcard-snippet">Tkinterのラベルの使い方について紹介。配置はpack()、grid()、place()３つの他、sideオプションやanchorオプションを紹介。文字の幅・高さや文字色・背景色の指定やフォントやサイズ、太さの変更も解説。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.08.11</div></div></div></div></a>
</div>



<p>ダブルクリックをするには、<strong>bindでイベントを追加する必要</strong>があります。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Tkinterでクリックイベントを付ける方法を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/bind/" title="【Python】Tkinterのbindメソッドでイベント検出" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinterのbindメソッドでイベント検出</div><div class="blogcard-snippet internal-blogcard-snippet">Pythonのtkinterのbindメソッドを解説。イベントハンドラとしてクリックイベントを例とし、さらにイベント一覧を紹介してます。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.05.04</div></div></div></div></a>
</div>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

# メインウィンドウの作成
root = tk.Tk()
root.title(&quot;リストボックス&quot;)

# エントリー（テキスト入力）の作成
entry = tk.Entry(root, width=40)
entry.pack(padx=10,pady=10)

# フレームを作成してリストボックスとスクロールバーをまとめる
frame = tk.Frame(root)
frame.pack(padx=10,pady=10)

# リストボックスの作成
listbox = tk.Listbox(frame, width=40, height=10)
listbox.pack(side=tk.LEFT)

# スクロールバーの作成
scrollbar = tk.Scrollbar(frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# リストボックスとスクロールバーを連動させる
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)

# エントリーの内容をリストボックスに追加する関数
def add_listbox(event = None): 
    item = entry.get()  
    if item: 
        listbox.insert(tk.END, item) 
        entry.delete(0, tk.END)
        
# リストボックスの項目を全て削除する関数
def reset_listbox():
    listbox.delete(0, tk.END)  # リストボックスの全項目を削除

# ボタン用のフレームを作成
button_frame = tk.Frame(root)
button_frame.pack(pady=10)

# 追加ボタンの作成
add_button = tk.Button(button_frame, text=&quot;追加&quot;, command=add_listbox)
add_button.grid(row=0, column=0, padx=5)

# リセットボタンの作成
reset_button = tk.Button(button_frame, text=&quot;リセット&quot;, command=reset_listbox)
reset_button.grid(row=0, column=1, padx=5)
# 項目を表示するラベルの作成
label = tk.Label(root, text=&quot;input text&quot;)
label.pack(padx=10,pady=10)

# リストボックスでダブルクリックした項目をラベルに表示する関数
def item(event):
    # ダブルクリックされた項目のインデックスを取得
    selected_index = listbox.curselection()
    if selected_index:
        # 選択された項目のテキストを取得してラベルに表示
        selected_item = listbox.get(selected_index)
        label.config(text=selected_item)

# リストボックスの項目をダブルクリックした際のイベントバインド
listbox.bind(&quot;&lt;Double-Button-1&gt;&quot;, item)

# エントリーでEnterキーが押された時に追加するようにバインド
entry.bind(&quot;&lt;Return&gt;&quot;, add_listbox)

# メインループの開始
root.mainloop()</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「root」：メインウィンドウを保持する変数。アプリケーションのウィンドウそのものを表しています。<br>「entry」：ユーザーが入力するテキストフィールドの変数。ユーザーが文字列を入力できる領域を提供します。<br>「frame」：リストボックスとスクロールバーをまとめて配置するためのフレーム。UI要素をグループ化するためのものです。<br>「listbox」：複数の項目を表示するリストボックス。ユーザーが複数の項目から選択することができる要素です。<br>「scrollbar」：リストボックスのスクロールを制御するためのスクロールバー。<br>「button_frame」：追加ボタンとリセットボタンをまとめて配置するフレーム。<br>「add_button」：エントリーに入力されたテキストをリストボックスに追加するボタン。<br>「reset_button」：リストボックスの全項目を削除するボタン。<br>「label」：リストボックスの項目を選択した時に、そのテキストを表示するためのラベル。</p>



<ul class="wp-block-list">
<li><strong>関数・メソッド</strong></li>
</ul>



<p><strong>add_listbox関数</strong><br>この関数は、エントリーに入力された文字列を取得し、リストボックスに追加します。<br>入力が空白でない場合のみ、エントリーから文字列を取得し、<br>それをリストボックスの最後に追加します。</p>



<p>追加後、エントリーの内容をクリアします（空にします）。<br>イベント引数（event）は、Enterキーが押された際にも<br>この関数が呼び出されるように設定されています。</p>



<p><strong>reset_listbox関数</strong><br>この関数は、リストボックス内の全ての項目を削除します。<br>delete(0, tk.END)で、リストボックスの最初の項目から最後の項目まで全てを消去しています。</p>



<p><strong>item関数</strong><br>この関数は、リストボックス内でダブルクリックされた項目のテキストを取得、ラベルに表示します。</p>



<p>リストボックスの選択された項目のインデックスを取得し、<br>対応するテキストを取得してラベルの内容を変更します。</p>



<h2 class="wp-block-heading">実演</h2>



<p>Entryウィジェットを使用して、<strong>ユーザーがリストに追加する文字列を入力できるテキスト入力フィールドを設置</strong>します。</p>



<p>その後、ListboxとScrollbarを作成し、<strong>リストボックス内の項目が多くなった際にスクロール</strong>して項目を確認できるように設定します。</p>



<p>追加ボタンをクリックすると、入力されたテキストがリストボックスに追加され、リ<strong>セットボタンを押すとリスト内の全項目が削除</strong>されます。</p>



<p>リストボックス内の項目をダブルクリックすると、<strong>その項目のテキストがラベルに表示</strong>される仕組みです。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>Tkinterのリストボックスを使うことで、<br>複数の項目を表示・選択するインターフェースを簡単に作成できます。</p>



<p>スクロールバーやボタンを使った追加・削除機能も加えることで、<br>ユーザーにとって使いやすいアプリケーションを開発可能です。</p>



<p>オプションを活用して、デザインや操作性を調整し、より高品質なGUIアプリを作成できます。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/tkinter-list-box/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】Tkinterラジオボタンの使い方、グループ化</title>
		<link>https://alicia-ing.com/programming/python/tkinter-radio-button/</link>
					<comments>https://alicia-ing.com/programming/python/tkinter-radio-button/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Fri, 20 Sep 2024 06:34:04 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=6989</guid>

					<description><![CDATA[Tkinterは、Pythonに標準搭載されているライブラリで、ラジオボタンは、ユーザーに複数の選択肢から一つを選ばせる場面でよく使われます。 本記事では、Tkinterラジオボタン(radio button)をどうやっ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<p>ラジオボタンの選択でラベルの表示・非表示にして、文字、色を変更する。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="950" src="https://alicia-ing.com/wp-content/uploads/2024/09/complete-1.gif" alt="" class="wp-image-7004"/></figure>
</div></div>



<p>Tkinterは、Pythonに標準搭載されているライブラリで、ラジオボタンは、ユーザーに複数の選択肢から一つを選ばせる場面でよく使われます。</p>



<p>本記事では、Tkinter<strong>ラジオボタン(radio button)</strong>をどうやって使うのか、そして複数のラジオボタンをグループ化する方法について詳しく解説します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>Pythonを学び始めたばかりで、GUIアプリケーションの作り方を知りたい人</li>



<li>Tkinterでラジオボタンを使った選択肢を実装したい人</li>



<li>ユーザーインターフェースのデザインを簡単に試したい人複数のラジオボタンをグループ化する方法を理解したい人</li>



<li>Tkinterを使ってイベント処理を組み込んだインタラクティブなアプリケーションを作りたい人</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">画面（ウィンドウ）作成</h2>



<p>TkinterでGUIアプリを作成する際、まず最初に行うのがウィンドウの作成です。<br><strong>tk.Tk()を使ってメインウィンドウを生成</strong>し、ウィンドウ内にウィジェットを配置していきます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

root = tk.Tk()  # メインウィンドウを作成
root.title(&quot;タイトル名&quot;)  # ウィンドウのタイトルを設定
root.geometry(&quot;300x200&quot;)  # ウィンドウサイズを指定（幅x高さ）
root.mainloop()</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="343" src="https://alicia-ing.com/wp-content/uploads/2024/09/widget-1024x343.webp" alt="" class="wp-image-6997" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/widget-1024x343.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/widget-300x101.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/widget-768x258.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/widget.webp 1169w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>ウィンドウの大きさやタイトルを設定することで、見た目を調整</strong>できます。</p>



<p>これがユーザーとのインターフェースの基盤となる部分です。</p>



<h2 class="wp-block-heading">ラジオボタンの作成</h2>



<p>ラジオボタンは、<strong>複数の選択肢から1つだけ選べるようにするためのウィジェット</strong>です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>radio = tk.Radiobutton(root, text=&quot;radio button&quot;)
radio.pack()  # ウィンドウにラジオボタンを配置</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="337" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio_button-1024x337.webp" alt="" class="wp-image-6998" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/radio_button-1024x337.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/radio_button-300x99.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/radio_button-768x253.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/radio_button.webp 1170w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>さらに、tk.Radiobutton()を使って作成し、<strong>variableオプションで選択結果を保持する変数を指定</strong>することもできます。</p>



<p>これにより、ユーザーがどのボタンを選択したかをプログラムで取得できるようになります。</p>



<h3 class="wp-block-heading">ラジオボタンを使用する用途</h3>



<p>ラジオボタンの用途は、多岐に広がり使用することでユーザビリティの向上につながります。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-thumbs-up"><span class="tab-caption-box-label-text block-box-label-text box-label-text">ラジオボタンの用途</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>色やデザインのオプション選択</li>



<li>性別や地域の選択フォーム</li>



<li>設定画面でのモード選択（例：ダークモードやライトモード）</li>



<li>アンケートでの単一選択</li>



<li>ユーザーがひとつの答えを選ばなければならない場面</li>
</ul>
</div></div>



<h2 class="wp-block-heading">オプション一覧（色・フォントなど）</h2>



<p>ラジオボタンを使用する際、<strong>表示されるテキストや色、フォント、大きさなどのデザインを変更</strong>することでより見やすく、使いやすいUIを作成できます。<br>fgで文字色、fontでフォントスタイル、padxとpadyでボタン間のスペースを調整できます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>radio = tk.Radiobutton(root, text=&quot;radio button&quot;, variable=color_var, value=&quot;radio button&quot;, fg=&quot;red&quot;, font=(&quot;Arial&quot;, 12))
radio.pack(padx=20, pady=5)</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="462" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio-option-1024x462.webp" alt="" class="wp-image-6999" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/radio-option-1024x462.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-option-300x135.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-option-768x346.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-option.webp 1290w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">ラジオボタンを複数（グループ化）する</h2>



<p>複数のラジオボタンをグループ化するには、<strong>共通のvariableを指定するだけで可能</strong>です。</p>



<p>異なる選択肢が同じ変数に関連付けられていることで、1つのグループとして扱われ、ユーザーはその中から1つだけ選択できます。</p>



<p>これにより、選択肢が直感的に分かりやすくなります。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>colors = [&quot;黒&quot;, &quot;赤&quot;, &quot;青&quot;, &quot;緑&quot;]
for color in colors:
    radio = tk.Radiobutton(root, text=color, variable=color_var, value=color)
    radio.pack(anchor=&#39;w&#39;)  # 左寄せで配置</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="298" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio-vertical-1024x298.webp" alt="" class="wp-image-7000" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/radio-vertical-1024x298.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-vertical-300x87.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-vertical-768x223.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-vertical.webp 1331w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>配置には、<strong>anchorオプション</strong>を使います。<br>注意点は、左（left）ではなく、方角で西(west)を使用します。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-light-green-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#8bc34a"><div class="tab-caption-box-label block-box-label box-label fab-graduation-cap"><span class="tab-caption-box-label-text block-box-label-text box-label-text">anchor（配置の指定）</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>n : 北（上側）に配置</li>



<li>ne : 北東（右上）に配置</li>



<li>e : 東（右側）に配置</li>



<li>se : 南東（右下）に配置</li>



<li>s : 南（下側）に配置</li>



<li>sw : 南西（左下）に配置</li>



<li>w : 西（左側）に配置</li>



<li>nw : 北西（左上）に配置</li>



<li>center : 中央に配置（デフォルト）</li>
</ul>
</div></div>



<h3 class="wp-block-heading">縦、横並びの方法</h3>



<p>ラジオボタンを縦にするには、デフォルトで列になります。</p>



<p>横に並べるには、pack()メソッドの<strong>sideオプション</strong>やgrid()メソッドを使います。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code># 横に並べる場合
radio.pack(side=&#39;left&#39;)</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="311" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio-side-1024x311.webp" alt="" class="wp-image-7001" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/radio-side-1024x311.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-side-300x91.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-side-768x233.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/radio-side.webp 1334w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>これにより、複数のラジオボタンを任意のレイアウトで配置することが可能です。</p>



<h2 class="wp-block-heading">初期値を指定して、選択した値に更新</h2>



<p>ユーザーがラジオボタンを選択した後、その選択された値を取得するには、<strong>variable.get()を使用</strong>します。</p>



<p>variable.get()メソッドで初期値を指定します。<br>この値はプログラム開始時に設定したデフォルト値です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>selected_color = color_var.get(value=&quot;初期値&quot;)  # 初期値を取得</code></pre></div>



<p>例えば、<strong>色を選択する際に最初にどの色が選ばれているか確認</strong>するために使えます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

def show_selected():
    selected_color = color_var.get()  # 現在選択されている値を取得
    print(f&quot;選択された色は: {selected_color}&quot;)

root = tk.Tk()  # メインウィンドウを作成
root.title(&quot;タイトル名&quot;)  # ウィンドウのタイトルを設定
root.geometry(&quot;300x200&quot;)  # ウィンドウサイズを指定（幅x高さ）

color_var = tk.StringVar(value=&quot;黒&quot;)  # 選択結果を保持する変数

# ラジオボタンの作成
radio_black = tk.Radiobutton(root, text=&quot;黒&quot;, variable=color_var, value=&quot;黒&quot;, command=show_selected)
radio_black.pack()

radio_red = tk.Radiobutton(root, text=&quot;赤&quot;, variable=color_var, value=&quot;赤&quot;, command=show_selected)
radio_red.pack()

radio_blue = tk.Radiobutton(root, text=&quot;青&quot;, variable=color_var, value=&quot;青&quot;, command=show_selected)
radio_blue.pack()

root.mainloop()</code></pre></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="950" src="https://alicia-ing.com/wp-content/uploads/2024/09/default_color.gif" alt="" class="wp-image-7002"/></figure>



<h3 class="wp-block-heading">イベント処理・追加方法</h3>



<p>既に使用していますが、ラジオボタンで選択されたときに特定の処理を実行するには、<strong>commandオプション</strong>を使用します。</p>



<p>これにより、ラジオボタンがクリックされたときに自動的に指定された関数が呼び出され、イベント処理が追加されます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>radio = tk.Radiobutton(root, text=&quot;赤&quot;, variable=color_var, value=&quot;赤&quot;, command=update_label)
radio.pack()</code></pre></div>



<h2 class="wp-block-heading">ラジオボタンの選択でラベルの表示と文字、色を変更</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/value-update-1024x528.webp" alt="" class="wp-image-7003" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/value-update-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/value-update-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/value-update-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/value-update-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/value-update.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>ラジオボタンで選択された値に応じて、ラベルのテキストや色を変更する処理を行います。選択された色を取得し、ラベルの文字を更新します。</p>



<p>また、特定の選択肢でラベルを非表示にすることも可能です。</p>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

def update_label():
    selected_color = color_var.get()
    if selected_color == &quot;非表示&quot;:
        label.pack_forget()  # ラベルを非表示にする
    else:
        label.config(text=f&quot;{selected_color}色で表示しています&quot;, fg=get_color(selected_color))
        label.pack()  # ラベルを再表示する

def get_color(color_name):
    color_dict = {
        &quot;黒&quot;: &quot;black&quot;,
        &quot;赤&quot;: &quot;red&quot;,
        &quot;青&quot;: &quot;blue&quot;,
        &quot;緑&quot;: &quot;green&quot;
    }
    return color_dict.get(color_name, &quot;black&quot;)

# ウィンドウの設定
root = tk.Tk()
root.title(&quot;色選択アプリ&quot;)
root.geometry(&quot;300x200&quot;)

# ラジオボタンの値を保持する変数
color_var = tk.StringVar(value=&quot;黒&quot;)

# ラジオボタンの設定
colors = [&quot;黒&quot;, &quot;赤&quot;, &quot;青&quot;, &quot;緑&quot;, &quot;非表示&quot;]
for color in colors:
    rb = tk.Radiobutton(root, text=color, variable=color_var, value=color, command=update_label)
    rb.pack(anchor=&#39;w&#39;, padx=20, pady=5)

# ラベルの初期設定
label = tk.Label(root, text=&quot;黒色で表示しています&quot;, fg=&quot;black&quot;)
label.pack()

# ウィンドウのループ処理
root.mainloop()</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「tkinter」：インストールは不要で、Pythonに標準で付属しているためすぐに使用可能です。</p>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「root」：Tkウィンドウオブジェクトで、GUIアプリケーションのメインウィンドウを表します。<br>「color_var」：tk.StringVar()で作成され、ラジオボタンの選択した色を保持します。初期値は「黒」に設定されています。<br>「label」：tk.Labelオブジェクトで、選択された色のテキストを表示するためのラベルです。初期値は「黒色で表示しています」。</p>



<ul class="wp-block-list">
<li><strong>関数・メソッド</strong></li>
</ul>



<p>update_label関数<br>選択された色に基づいてラベルの表示を更新する処理を行います。<br>ラジオボタンで「非表示」が選択された場合、label.pack_forget()を使ってラベルを非表示にし、それ以外の色が選択された場合はlabel.config()でラベルのテキストと色を更新し、再表示します。</p>



<p>get_color関数<br>渡された色名（&#8221;黒&#8221;、&#8221;赤&#8221;、&#8221;青&#8221;、&#8221;緑&#8221;）を英語の色名（&#8221;black&#8221;、&#8221;red&#8221;、&#8221;blue&#8221;、&#8221;green&#8221;）に変換します。color_dictを使用し、該当しない場合はデフォルトで黒を返します。</p>



<h2 class="wp-block-heading">実演</h2>



<p>ラジオボタンの作成：5つのラジオボタン（黒、赤、青、緑、非表示）をウィンドウ内に作成し、それぞれの選択肢をクリックすると関数が呼び出して、ラベルと表示を更新します。</p>



<p>また、「非表示」が選択された場合にはラベルが非表示になる処理を実装しています。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>Tkinterを使用したラジオボタンの実装は、シンプルでありながら強力な機能を提供します。<br>ラジオボタンを使ったアプリケーションの構築方法を理解し、場面で活用してみてください。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/tkinter-radio-button/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】Tkinterエントリー作成、初期値の取得を解説</title>
		<link>https://alicia-ing.com/programming/python/tkinter-entry/</link>
					<comments>https://alicia-ing.com/programming/python/tkinter-entry/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Wed, 18 Sep 2024 07:12:43 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=6949</guid>

					<description><![CDATA[PythonでGUIアプリケーションを作成するとき、ユーザーからの入力を受け取るために使用されるのが「Tkinter」のエントリーボックスです。 エントリーボックスを自由自在にカスタマイズできるようになれば、ユーザーとの [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="944" src="https://alicia-ing.com/wp-content/uploads/2024/09/complete.gif" alt="" class="wp-image-6964"/></figure>
</div></div>



<p>PythonでGUIアプリケーションを作成するとき、ユーザーからの入力を受け取るために使用されるのが「Tkinter」のエントリーボックスです。</p>



<p>エントリーボックスを自由自在にカスタマイズできるようになれば、ユーザーとのやり取りをよりスムーズに行えるインターフェースが構築できるようになります。</p>



<p>この記事では、Tkinterのエントリーウィジェットを使って、文字列の取得や表示、エントリーボックスのサイズ変更、初期値の設定など、基本的な使い方を解説します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>PythonでGUIアプリケーションを開発したい初心者</li>



<li>Tkinterを使ってフォームや入力フィールドを作成したい方</li>



<li>エントリーウィジェットの基本的な設定や使い方を学びたい方</li>



<li>ユーザーの入力を取得し、リアルタイムで表示する方法を知りたい方</li>



<li>入力フィールドに対する初期値の設定やリセット方法に興味がある方</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">画面（ウィンドウ）作成</h2>



<p>Tkinterを使ったGUIアプリケーションは、最初に画面、つまりウィンドウを作成するところから始まります。</p>



<p>このウィンドウがユーザーとの対話の場となり、その上にボタンやエントリーボックスなどのウィジェットを配置していきます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

root = tk.Tk()
root.title(&quot;Sample&quot;)
root.geometry(&quot;300x200&quot;)  # サイズを指定
root.mainloop()</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="380" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1024x380.webp" alt="" class="wp-image-6957" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1024x380.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-300x111.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-768x285.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack.webp 1055w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>ウィンドウサイズの設定やタイトルの指定など、<br>ユーザーにとって使いやすいデザインを作ることができます。</p>



<h2 class="wp-block-heading">エントリー(Entry)作成</h2>



<p>エントリーウィジェットは、ユーザーが文字を入力するための入力フィールドです。<br>Tkinterでは、Entryクラスを使って簡単に作成できます。</p>



<p>ここでは、エントリーボックスをウィンドウに配置、サイズや位置を調整する方法を見ていきます。</p>



<h3 class="wp-block-heading">Pack()</h3>



<p>pack()メソッドは、ウィジェットをウィンドウに配置する際に、<br>シンプルで自動的な位置決定を行う方法です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>entry = tk.Entry(root)
entry.pack(side=tk.TOP, padx=10, pady=10)</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="380" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-1024x380.webp" alt="" class="wp-image-6958" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-1024x380.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-300x111.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-768x285.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1.webp 1055w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>ウィジェットを上から順番に詰め込むように配置したい場合に使います。</p>



<h3 class="wp-block-heading">grid()</h3>



<p>grid()メソッドは、ウィジェットを行と列のグリッドに沿って配置する方法です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>entry = tk.Entry(root)
entry.grid(row=0, column=0, padx=10, pady=10)</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="350" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-1024x350.webp" alt="" class="wp-image-6959" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-1024x350.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-300x103.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-768x263.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid.webp 1094w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>より柔軟なレイアウトが可能で、複数のウィジェットを整理して配置したい場合に適しています。</p>



<h3 class="wp-block-heading">Place()</h3>



<p>place()メソッドは、ウィジェットをピクセル単位で正確に配置するための方法です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>entry = tk.Entry(root)
entry.place(x=50, y=50)</code></pre></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1006" height="410" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-place.webp" alt="" class="wp-image-6961" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-place.webp 1006w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-place-300x122.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-place-768x313.webp 768w" sizes="(max-width: 1006px) 100vw, 1006px" /></figure>



<p>ウィンドウ上の特定の位置にウィジェットを置く必要がある場合に便利です。</p>



<h2 class="wp-block-heading">オプション一覧（色・フォントなど）</h2>



<p>Tkinterのエントリーボックスは、色、フォント、サイズなどをカスタマイズできます。<br>例えば、入力フィールドの背景色を変更したり、フォントの種類やサイズを指定することが可能です。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-1024x315.webp" alt="" class="wp-image-6962" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-1024x315.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-300x92.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-768x236.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-option.webp 1258w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>entry = tk.Entry(root, bg=&quot;lightblue&quot;, font=(&quot;Arial&quot;, 12), width=30)
entry.pack()</code></pre></div>



<h2 class="wp-block-heading">Entryウィジェットから文字列の取得・セット(初期値設定)・クリア</h2>



<p>エントリーボックスに入力された文字列を取得するには、get()メソッドを使います。<br>また、insert()メソッドで初期値を設定したり、delete()メソッドで入力をクリアすることも可能です。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="426" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-1024x426.webp" alt="" class="wp-image-6963" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-1024x426.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-300x125.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-768x320.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-value.webp 1148w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code># 文字列の取得
text = entry.get()

# 文字列のセット
entry.insert(0, &quot;アリッシアの朝&quot;)

# クリア
entry.delete(0, tk.END)</code></pre></div>



<p>さらに改良をして、ボタンを押すと、テキストを取得し、エントリーの文字を削除するようにします。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Pythonでボタンを使う方法を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-button/" title="【Python】Tkinterボタン(Button)の作成" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-button-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinterボタン(Button)の作成</div><div class="blogcard-snippet internal-blogcard-snippet">PythonのTkinterでGUIボタンを構築する方法を紹介します。標準ボタンを作成したり配置したり、さらに色を指定して背景や文字を変更することも簡単にできます。Tkinterでアプリをつくるときには、ボタンは必須です。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.03.11</div></div></div></div></a>
</div>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Pythonでラベルを使う方法を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/tkinter-label/" title="【Python】TkinterのLabel（ラベル）使い方" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2022/12/tkinter-label-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】TkinterのLabel（ラベル）使い方</div><div class="blogcard-snippet internal-blogcard-snippet">Tkinterのラベルの使い方について紹介。配置はpack()、grid()、place()３つの他、sideオプションやanchorオプションを紹介。文字の幅・高さや文字色・背景色の指定やフォントやサイズ、太さの変更も解説。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.08.11</div></div></div></div></a>
</div>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk

def display_text():
    # エントリーから文字を取得
    text = entry.get()
    # ラベルに表示
    label2.config(text=text)
    # エントリーをクリア
    entry.delete(0, tk.END)

root = tk.Tk()
root.title(&quot;Sample&quot;)
root.geometry(&quot;300x200&quot;)  # サイズを指定

# ラベル 
label1 = tk.Label(root, text=&quot;名前を入力してください&quot;)
label1.pack(pady=10)

# エントリーウィジェット
entry = tk.Entry(root)
entry.insert(0, &quot;アリッシアの朝&quot;)
entry.pack(pady=10)

# ボタン
button = tk.Button(root, text=&quot;取得&quot;, command=display_text)
button.pack(pady=10)

# ラベル (取得した文字を表示するため)
label2 = tk.Label(root, text=&quot;&quot;)
label2.pack(pady=10)

root.mainloop()</code></pre></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="944" src="https://alicia-ing.com/wp-content/uploads/2024/09/get.gif" alt="" class="wp-image-6966"/></figure>



<p>ユーザーにとって使いやすいインターフェースを作ることができます。</p>



<h2 class="wp-block-heading">入力値をリアルタイムで表示</h2>



<p>ユーザーがエントリーボックスに入力した内容を<strong>リアルタイム</strong>で、画面に反映させる方法について解説します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>def show_input(*args):
    print(entry.get())

entry_var = tk.StringVar()
entry_var.trace(&quot;w&quot;, show_input)

entry = tk.Entry(root, textvariable=entry_var)
entry.pack()</code></pre></div>



<p>traceメソッドを使って、入力が変更されるたびに反応する仕組みを作ることができます。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="944" src="https://alicia-ing.com/wp-content/uploads/2024/09/real-time.gif" alt="" class="wp-image-6968"/></figure>



<p>print()をラベルに変更して、Tkinter上に表示させることも可能です。</p>



<h2 class="wp-block-heading">Enter(Return)キーで入力値を取得</h2>



<p>ユーザーが入力を終えた後、Enterキーを押したタイミングでエントリーボックスから入力値を取得する方法を紹介します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>def on_enter(event):
    print(&quot;入力値:&quot;, entry.get())

entry.bind(&quot;&lt;Return&gt;&quot;, on_enter)</code></pre></div>



<p>bindを使うことでイベントを追加できます。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>bindの使い方を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/bind/" title="【Python】Tkinterのbindメソッドでイベント検出" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/09/bind-1-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinterのbindメソッドでイベント検出</div><div class="blogcard-snippet internal-blogcard-snippet">Pythonのtkinterのbindメソッドを解説。イベントハンドラとしてクリックイベントを例とし、さらにイベント一覧を紹介してます。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.05.04</div></div></div></div></a>
</div>



<p>これにより、フォーム送信や次の処理に進む操作を自然な形で実現できます。</p>



<h2 class="wp-block-heading">Pythonでログインフォームを作成する</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/login-1024x528.webp" alt="" class="wp-image-6969" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/login-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/login-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/login-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/login-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/login.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Pythonでログインフォームを作るには、TkinterのEntryが有効です。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-bolt"><span class="tab-caption-box-label-text block-box-label-text box-label-text">Pythonでログインフォームをつくる</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>ログイン画面の作成：エントリーウィジェットでユーザー名とパスワードを入力します。</li>



<li>入力値の検証：get()メソッドを使ってエントリーから値を取得し、<br>正しいかどうかを確認します。</li>



<li>画面遷移：正しいユーザー名とパスワードが入力されると、<br>新しいウィンドウ（画面B）が開き、エントリーボックスで新しいパスワードを設定できます。</li>



<li>パスワードの変更：新しいパスワードが正しい形式かどうかを正規表現でチェックし、<br>問題がなければ変更が完了します。</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Tkinterの画面遷移を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/change_screen/" title="【Python】Tkinter画面遷移-複数ウィンドウをクラス化" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinter画面遷移-複数ウィンドウをクラス化</div><div class="blogcard-snippet internal-blogcard-snippet">Tkinterの複数ウィンドウを画面遷移するには、pack_forget()メソッドを使います。ボタンでクリックすると表示と非表示をして画面切り替えをします。複雑な画面遷移は、def関数では読みにくいのでクラス化して可読性を上げます。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.03.10</div></div></div></div></a>
</div>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import tkinter as tk
from tkinter import messagebox
import re

# 初期の正しいユーザー名とパスワード
initial_username = &quot;アリッシア&quot;
initial_password = &quot;Alicia-ing&quot;

# グローバル変数を使ってパスワードを更新可能にする
current_password = initial_password

# パスワードのバリデーション関数
def validate_password(password):
    # 大文字、小文字、記号を含むかチェック
    if (re.search(r&#39;[A-Z]&#39;, password) and  # 大文字
        re.search(r&#39;[a-z]&#39;, password) and  # 小文字
        re.search(r&#39;[\W_]&#39;, password)):    # 記号
        return True
    else:
        return False

# 画面Aのログイン処理
def login():
    global current_password
    username = entry_username.get()
    password = entry_password.get()

    if username == &quot;&quot; or password == &quot;&quot;:
        message_label.config(text=&quot;入力を完了してください&quot;, fg=&quot;red&quot;)
    elif username != initial_username or password != current_password:
        message_label.config(text=&quot;パスワードが異なります&quot;, fg=&quot;red&quot;)
        entry_username.delete(0, tk.END)  # 入力フィールドをクリア
        entry_password.delete(0, tk.END)  # 入力フィールドをクリア
    else:
        # 画面Bへ遷移
        open_screen_b(username)

# 画面Bを開く関数
def open_screen_b(username):
    screen_a.withdraw()  # 画面Aを非表示にする
    screen_b = tk.Toplevel()  # 新しいウィンドウ（画面B）
    screen_b.title(&quot;画面B&quot;)
    screen_b.geometry(&quot;300x200&quot;)  # 画面サイズの指定

    label_greeting = tk.Label(screen_b, text=f&quot;Hello, {username}&quot;, font=(&quot;Arial&quot;, 14))
    label_greeting.pack(pady=10)

    label_new_password = tk.Label(screen_b, text=&quot;新しいパスワード:&quot;)
    label_new_password.pack(pady=5)

    new_password_entry = tk.Entry(screen_b)
    new_password_entry.pack(pady=5)

    # エンターキーが押されたらパスワード変更を実行
    new_password_entry.bind(&quot;&lt;Return&gt;&quot;, lambda event: change_password())

    def change_password():
        new_password = new_password_entry.get()
        if validate_password(new_password):
            global current_password
            current_password = new_password  # パスワードを更新
            messagebox.showinfo(&quot;成功&quot;, &quot;パスワードが変更されました&quot;)
            screen_b.destroy()  # 画面Bを閉じる
            screen_a.deiconify()  # 画面Aを再表示する
        else:
            messagebox.showerror(&quot;エラー&quot;, &quot;もう一度作成してください (大文字, 小文字, 記号を含む必要があります)&quot;)

    change_button = tk.Button(screen_b, text=&quot;変更&quot;, command=change_password)
    change_button.pack(pady=20)

# メインウィンドウ（画面A）
screen_a = tk.Tk()
screen_a.title(&quot;ログイン画面&quot;)
screen_a.geometry(&quot;300x250&quot;)  # 画面サイズの指定

# ユーザー名入力フィールド
label_username = tk.Label(screen_a, text=&quot;ユーザー名:&quot;)
label_username.pack(pady=5)

entry_username = tk.Entry(screen_a)
entry_username.pack(pady=5)

# パスワード入力フィールド
label_password = tk.Label(screen_a, text=&quot;パスワード:&quot;)
label_password.pack(pady=5)

entry_password = tk.Entry(screen_a, show=&quot;*&quot;)  # パスワード非表示
entry_password.pack(pady=5)

# メッセージラベル（エラーメッセージ表示用）
message_label = tk.Label(screen_a, text=&quot;&quot;)
message_label.pack(pady=5)

# ログインボタン
login_button = tk.Button(screen_a, text=&quot;ログイン&quot;, command=login)
login_button.pack(pady=20)

screen_a.mainloop()</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「tkinter」：Pythonの標準ライブラリで、GUIアプリケーションを作成するために使用。「tkinter.messagebox」：GUIアプリケーション内で情報やエラーメッセージを表示するダイアログボックスを提供する。<br>「re」：正規表現を利用した文字列のパターンマッチングを行うために使用。パスワードのバリデーションに活用されている。</p>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「initial_username」：初期の正しいユーザー名を保持する変数。ログイン時にユーザー入力と比較するために使用。<br>「initial_password」：初期の正しいパスワードを保持する変数。ログイン時にパスワード入力と比較するために使用。<br>「current_password」：現在のパスワードを保持するグローバル変数。パスワード変更後に更新され、ログイン時に使用される。<br>「screen_a」：ログイン画面（画面A）のウィンドウオブジェクトを保持。GUIのメインウィンドウを表す。<br>「screen_b」：パスワード変更画面（画面B）のウィンドウオブジェクト。ログイン成功後に新たに作成される。<br>「entry_username」：ユーザー名を入力するテキストフィールド。ユーザーがログイン時に使用する。<br>「entry_password」：パスワードを入力するテキストフィールド。ユーザーがログイン時に使用する。<br>「message_label」：ログイン時のエラーメッセージや案内メッセージを表示するためのラベル。</p>



<ul class="wp-block-list">
<li><strong>クラス（関数・メソッド）</strong></li>
</ul>



<p>「validate_password」関数<br>正規表現を使用して、入力されたパスワードが大文字、小文字、記号を含むかをチェックし、条件を満たす場合にTrueを返す。それ以外の場合はFalseを返す。</p>



<p>「login」関数<br>処理の説明を文章にする。<br>ユーザーが入力したユーザー名とパスワードを検証する。入力が空の場合や不正な組み合わせの場合には、エラーメッセージを表示する。正しいユーザー名とパスワードが入力された場合は、画面Bに遷移する。</p>



<p>「open_screen_b」関数<br>画面Aを非表示にして、新しいウィンドウ（画面B）を表示し、ユーザーに挨拶メッセージと新しいパスワードを入力させる。パスワード変更のための処理もこの関数内で行われる。</p>



<p>「change_password」関数<br>ユーザーが入力した新しいパスワードが「validate_password」で有効かを確認し、有効な場合は現在のパスワードを更新し、画面Bを閉じて画面Aを再表示する。無効な場合はエラーメッセージを表示する。</p>



<h3 class="wp-block-heading">実演</h3>



<p>ログイン画面が表示されて、ユーザーが入力した情報に基づいて次の画面に遷移する処理を行います。</p>



<p>エントリーウィジェットにユーザー名とパスワードを入力し、それを検証します。<br>もし正しいユーザー名とパスワードが入力されると、次の画面が表示され、<br>パスワードを変更できるようになります。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>Tkinterを使ってエントリーボックスを作成し、文字列の取得やセット、クリア、そしてリアルタイムでの表示といった操作を行う方法について学びました。<br>エントリーウィジェットは、ユーザーとのインタラクションを強化するために欠かせない要素です。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/tkinter-entry/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】合成音声pyttsx3使い方-テキストを読み上げ</title>
		<link>https://alicia-ing.com/programming/python/pyttsx3-text-to-speech/</link>
					<comments>https://alicia-ing.com/programming/python/pyttsx3-text-to-speech/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Mon, 16 Sep 2024 05:12:01 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=6911</guid>

					<description><![CDATA[Pythonでテキストを音声として読み上げたいときには、オフラインで動作する合成音声ライブラリ「pyttsx3」を使うと便利です。 このライブラリは、簡単にテキストを音声に変換でき、速度や音声の種類も調整可能です。プログ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="729" src="https://alicia-ing.com/wp-content/uploads/2024/09/complete-1024x729.webp" alt="" class="wp-image-6922" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/complete-1024x729.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/complete-300x214.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/complete-768x547.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/complete.webp 1300w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div></div>



<p>Pythonでテキストを音声として読み上げたいときには、<br>オフラインで動作する合成音声ライブラリ「<strong>pyttsx3</strong>」を使うと便利です。</p>



<p>このライブラリは、簡単にテキストを音声に変換でき、速度や音声の種類も調整可能です。<br>プログラムにナレーションを追加したり、読み上げアプリを開発したりする際に活躍します。</p>



<p>本記事では、pyttsx3の基本的な使い方から、商用利用の可否や対応言語について詳しく解説します。<br>公式サイト：「<a target="_self" href="https://pypi.org/project/pyttsx3/" data-type="link" data-id="https://pypi.org/project/pyttsx3/">Pyttsx3公式ページ</a>」</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>Pythonでテキスト読み上げ機能を実装したい人</li>



<li>オフラインで動作する音声合成ライブラリを探している人</li>



<li>商用利用可能な音声合成ツールを検討している人</li>



<li>Pythonでナレーション付きのアプリケーションを作成したい人</li>



<li>朗読ソフトや支援ツールを自作したい人</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">pyttsx3とは？</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx3-1024x528.webp" alt="" class="wp-image-6917" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx3-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx3-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx3-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx3-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx3.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>pyttsx3は、Python用のテキスト読み上げライブラリで、<br><strong>コンピュータのローカルで音声合成</strong>を行います。</p>



<p>インストールは、<strong>コマンドプロンプト、ターミナル</strong>でできます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>pip install pyttsx3</code></pre></div>



<p>WindowsではSAPI5、MacOSではNSSpeechSynthesizer、Linuxではespeakを使用しており、<br><strong>さまざまなプラットフォームで簡単に利用</strong>できます。pyttsx</p>



<figure class="wp-block-table aligncenter"><div class="scrollable-table"><table><tbody><tr><td class="has-text-align-center" data-align="center">Windows</td><td class="has-text-align-center" data-align="center">sapi5</td></tr><tr><td class="has-text-align-center" data-align="center">Mac</td><td class="has-text-align-center" data-align="center">nsss</td></tr><tr><td class="has-text-align-center" data-align="center">Linux</td><td class="has-text-align-center" data-align="center">espeak</td></tr></tbody></table></div></figure>



<p>また、音声速度や音量、性別の調整が可能で、カスタマイズ性が高い点も特徴です。</p>



<h3 class="wp-block-heading">音声の読み上げ</h3>



<p>テキストを<strong>リアルタイムで音声として再生</strong>できます。<br>say()メソッドにテキストを入力し、runAndWait()メソッドで実行します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import pyttsx3

# エンジンの初期化
engine = pyttsx3.init()

# 読み上げるテキスト
engine.say(&quot;Hello, I am reading this text.&quot;)

# 読み上げ実行
engine.runAndWait()
</code></pre></div>



<h3 class="wp-block-heading">音声のプロパティ変更</h3>



<p>音声の再生速度、音量、音声の性別など、<strong>細かいプロパティを変更</strong>できます。<br>カスタマイズした音声合成が可能です。</p>



<p>速度150で音量90%、男性の声で「Hello alicia-ing」と読み上げます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import pyttsx3

engine = pyttsx3.init()

# 音量の設定（0.0 から 1.0）
engine.setProperty(&#39;volume&#39;, 0.9)

# 速度（WPM: words per minute）
engine.setProperty(&#39;rate&#39;, 150)

# 音声（性別）の変更
voices = engine.getProperty(&#39;voices&#39;)
engine.setProperty(&#39;voice&#39;, voices[0].id)  # 男性の声
#engine.setProperty(&#39;voice&#39;, voices[1].id)  # 女性の声

engine.say(&quot;Hello alicia-ing&quot;)
engine.runAndWait()</code></pre></div>



<h3 class="wp-block-heading">音声の保存</h3>



<p>テキストを音声ファイル（WAV形式）として保存することができます。<br><strong>save_to_file()メソッドを使用</strong>して、音声をファイルに書き出すことが可能です。</p>



<p>ただし、<strong>mp3ファイルは非対応</strong>です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>text= &quot;Hello alicia-ing&quot;
engine.save_to_file(text , &#39;voice.wav&#39;)</code></pre></div>



<h3 class="wp-block-heading">イベント制御</h3>



<p><strong>読み上げ開始、終了時にイベントをトリガー</strong>にして、プログラムを処理する。</p>



<p>再生が開始したら、「Start」とログを出力し、<br>再生が終了したら、「製作者と終わった時間」を取得して、ログに出力する。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import pyttsx3
from datetime import datetime

def onStart(name):
    print(&quot;Start&quot;)

def onEnd(name, completed):
    end_time = datetime.now().strftime(&quot;%H:%M:%S&quot;)  # 再生終了時刻を取得
    print(f&quot;End, presented: {name}, completed at: {end_time}&quot;)

engine = pyttsx3.init()

# イベントの接続
engine.connect(&#39;started-utterance&#39;, lambda name: onStart(&quot;Alicia&quot;))
engine.connect(&#39;finished-utterance&#39;, lambda name, completed: onEnd(&quot;Alicia&quot;, completed))

# 読み上げの設定と実行
engine.say(&quot;This will trigger events.&quot;)
engine.runAndWait()

</code></pre></div>



<h2 class="wp-block-heading">商用利用可能か？</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/commercial-use-1-1024x528.webp" alt="" class="wp-image-6918" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/commercial-use-1-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/commercial-use-1-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/commercial-use-1-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/commercial-use-1-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/commercial-use-1.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>pyttsx3はオープンソースライブラリであり、商用利用も可能です。</p>



<p>ただし、音声エンジンに依存する部分もあるため、<br><strong>合成音声エンジン自体のライセンス条件を確認</strong>する必要があります。</p>



<p>そのため、商用利用可能なGoogle-Text-to-Speechがおすすめです。<br>APIを取得すれば、Pythonからも操作できます。</p>



<div class="wp-block-cocoon-blocks-micro-text micro-text micro-copy micro-top"><span class="micro-text-content micro-content"><span class="micro-text-icon micro-icon fab-info-circle"></span>Google-Text-to-Speechの操作方法を紹介しています。</span></div>



<div class="wp-block-cocoon-blocks-blogcard blogcard-type bct-together">

<a target="_self" href="https://alicia-ing.com/programming/python/google-text-to-speech/" title="【Python】Google-Text-to-SpeechのAPIを取得し発話" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2024/11/google-text-to-speech-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2024/11/google-text-to-speech-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2024/11/google-text-to-speech-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2024/11/google-text-to-speech-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Google-Text-to-SpeechのAPIを取得し発話</div><div class="blogcard-snippet internal-blogcard-snippet">Google Text-to-SpeechのAPIをPythonで操作する方法を解説。商用利用や料金、音声のMP3保存についても詳しく紹介しています。APIの設定方法から実際の音声生成までカバーし、あらゆる用途で役立つ情報を提供します。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2024.11.25</div></div></div></div></a>
</div>



<h2 class="wp-block-heading">対応している言語は？</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/language-1024x528.webp" alt="" class="wp-image-6919" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/language-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/language-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/language-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/language-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/language.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>pyttsx3は、使用する音声エンジンに依存して、様々な言語に対応しています。<br>具体的には、英語、日本語、フランス語、ドイツ語など、多くの言語で音声合成が可能です。</p>



<p>ただし、エンジンやOSによっては、言語のサポート状況が異なります。</p>



<div class="wp-block-cocoon-blocks-balloon-ex-box-1 speech-wrap sb-id-2 sbs-stn sbp-l sbis-cb cf block-box not-nested-style cocoon-block-balloon"><div class="speech-person"><figure class="speech-icon"><img decoding="async" src="https://alicia-ing.com/wp-content/uploads/2023/05/cropped-alicia.webp" alt="筆者" class="speech-icon-image"/></figure><div class="speech-name">筆者</div></div><div class="speech-balloon">
<p><strong>Windowsでは、英語、日本語、フランス語</strong>はできた。ドイツ語もできたが英語？ってなった。<br>韓国語は発音できず、中国語は違う気がした。</p>
</div></div>



<h2 class="wp-block-heading">csvのテキストを一括でwavファイル化</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/txt-to-wav-1024x528.webp" alt="" class="wp-image-6920" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/txt-to-wav-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/txt-to-wav-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/txt-to-wav-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/txt-to-wav-1536x791.webp 1536w, https://alicia-ing.com/wp-content/uploads/2024/09/txt-to-wav.webp 1980w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>pyttsx3を使用してCSVファイル内のテキストを一括で音声にします。</p>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import pyttsx3
import csv

# pyttsx3エンジンの初期化
engine = pyttsx3.init()
rate = engine.getProperty(&#39;rate&#39;)
engine.setProperty(&#39;rate&#39;, rate-50)

# CSVファイルの読み込み
with open(&#39;word.csv&#39;, &#39;r&#39;, newline=&#39;&#39;, encoding=&#39;utf-8&#39;) as csvfile:
    reader = csv.reader(csvfile)
    
    # 全ての行をリストとして取得
    rows = list(reader)
    
    # 列ごとに処理
    for column in range(len(rows[0])):  # 列の数だけループ
        for index, row in enumerate(rows):
            if column &lt; len(row):  # 列のインデックスが範囲内かチェック
                text = row[column]  # セルの値を取得
                
                # 音声ファイルの保存先を決定 
                filename = f&#39;output_{index}.wav&#39;
                
                # 音声をテキストから生成し、WAVファイルとして保存
                engine.save_to_file(text, filename)
                print(f&#39;Saved: {filename}&#39;)
        
# 音声生成の実行
engine.runAndWait()</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「pyttsx3」：Pythonのテキストを音声に変換するためのライブラリ。テキストを音声ファイルに保存する機能が必要なため使用している。<br>「csv」：CSV（Comma-Separated Values）形式のファイルを読み込み、テキストデータを取得するために使用される。<br>Python標準ライブラリなので、インストール不要。</p>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「engine」：pyttsx3のエンジンを初期化し、音声合成のためのインスタンスを作成する。<br>「rate」：音声の速度を取得するために使用。通常のスピードよりも遅くするため、rate-50に設定される。<br>「csvfile」：CSVファイルを読み込むためのファイルオブジェクト。<br>「reader」：csv.readerによって、CSVファイルの内容を行ごとに読み込むリーダーオブジェクト。<br>「rows」：CSVファイルの全ての行をリストとして保持する。各行はリストの形式で格納される。<br>「index」：音声ファイルを保存するための番号。<br>「column」：CSVファイルの列インデックスを管理する変数。各列のデータを処理するために使われる。<br>「row」：CSVファイルの各行を指す変数。リスト形式で保持された各行のデータを処理するために使われる。<br>「text」：現在のセル（CSVの特定の行・列）の値をテキストとして保持する。<br>「filename」：音声ファイルを保存する際のファイル名。処理されているセルに基づき生成される。</p>



<ul class="wp-block-list">
<li><strong>関数・メソッド</strong></li>
</ul>



<p>「pyttsx3.init()」：音声エンジンを初期化し、音声合成のためのエンジンインスタンスが生成される。</p>



<p>「engine.getProperty(&#8216;rate&#8217;)」：現在設定されている音声の読み上げ速度を取得する。音声の読み上げ速度をカスタマイズするために使用される。</p>



<p>「engine.setProperty(&#8216;rate&#8217;, rate-50)」：音声の読み上げ速度をrate-50に設定する。pyttsx3は読み上げ速度が速すぎるので、<strong>半分ぐらいがおすすめ</strong>。</p>



<p>「csv.reader()」：CSVファイルを読み込み、行ごとのデータを取得するためのリーダーオブジェクトを返す。</p>



<p>「engine.save_to_file(text, filename)」：textで指定したテキストを音声に変換し、指定したファイル名filenameでWAV形式の音声ファイルに保存する。</p>



<p>「engine.runAndWait()メソッド」：すべての音声を処理し、音声合成を実行する。全てのテキストの音声化が完了するまで待機する。</p>



<ul class="wp-block-list">
<li><strong>その他</strong></li>
</ul>



<p>with open()：CSVファイルを読み込み、ファイル操作を行う。ファイルを開いた後は、自動的にクローズする。encoding=&#8217;utf-8&#8217;により、UTF-8形式でファイルを読み込む設定。</p>



<p>list(reader)：csv.readerオブジェクトから全ての行をリスト形式で取得し、rowsに保存する。<br><br>enumerate()関数：各行をインデックス付きで処理するために使用される。ループ内で行インデックスを取得しつつ、その行自体も同時に扱う。</p>



<h2 class="wp-block-heading">実演</h2>



<p>スクリプトを実行すると、csv（word.csv）に保管してあるテキストを読み込み、<br>wav形式で保存します。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="522" src="https://alicia-ing.com/wp-content/uploads/2024/09/csv-file-1024x522.webp" alt="" class="wp-image-6923" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/csv-file-1024x522.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/csv-file-300x153.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/csv-file-768x391.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/csv-file.webp 1119w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>保存先は、Pythonのスクリプトと同じ段落です。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>Pythonの合成音声ライブラリ「pyttsx3」の基本的な使い方とその機能について解説しました。</p>



<p>pyttsx3は、テキストの読み上げから、音声ファイルの生成、プロパティの変更まで、幅広い用途に対応します。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/pyttsx3-text-to-speech/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】PDF結合・分割｜PyPDF2の使い方</title>
		<link>https://alicia-ing.com/programming/python/pypdf-edit/</link>
					<comments>https://alicia-ing.com/programming/python/pypdf-edit/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Thu, 11 Jul 2024 12:00:12 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=6684</guid>

					<description><![CDATA[Pythonを使えば、複数のPDFファイルを1つに結合とPDFファイルを１つずつ分割することが簡単にできます。 本記事では、PyPDF2ライブラリを使用してPDFを分割や結合などの操作を実行する方法を詳しく解説します。  [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>PDFファイルを結合する。</li>
</ul>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/merger_pdf.gif" alt="" class="wp-image-6692"/></figure>



<ul class="wp-block-list">
<li>PDFを１ページずつ分割する。</li>
</ul>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/splitpdf.gif" alt="" class="wp-image-6693"/></figure>
</div></div>



<p>Pythonを使えば、<strong>複数のPDFファイルを1つに結合</strong>とPDFファイルを１つずつ分割することが簡単にできます。</p>



<p>本記事では、PyPDF2ライブラリを使用してPDFを分割や結合などの操作を実行する方法を詳しく解説します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>PythonでPDFを操作したい。</li>



<li>紙の書類をデジタル化し、管理したい</li>



<li>多数のPDFファイルを扱いたい人</li>



<li>学術論文や研究資料を整理する学生や研究者</li>



<li>PDFを利用したドキュメント管理を効率化したいエンジニア</li>
</ul>
</div></div>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>



<h2 class="wp-block-heading">PyPDF2の機能と使う場面</h2>



<p>PyPDF2は、PythonでPDFファイルを操作するためのライブラリです。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-light-green-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#8bc34a"><div class="tab-caption-box-label block-box-label box-label fab-thumbs-up"><span class="tab-caption-box-label-text block-box-label-text box-label-text">PyPDF2を使う場面</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li><strong>PDFの結合と分割</strong>: 複数のPDFファイルを一つにまとめる、PDFファイルをページ単位で分割。</li>



<li><strong>ページの抽出と追加</strong>: 特定のページを抽出、新しいページの追加。</li>



<li><strong>メタデータの操作</strong>: PDFのメタデータ（タイトル、著者、作成日など）の読み取り、変更。</li>
</ul>
</div></div>



<h3 class="wp-block-heading">PDFの結合</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import PyPDF2

# PDFファイルを読み込む
pdf1 = open(&#39;document1.pdf&#39;, &#39;rb&#39;)
pdf2 = open(&#39;document2.pdf&#39;, &#39;rb&#39;)

# PdfMergerオブジェクトを作成
merger = PyPDF2.PdfMerger()

# PDFファイルを追加
merger.append(pdf1)
merger.append(pdf2)

# 結合されたPDFをファイルとして書き出し
with open(&#39;new_document.pdf&#39;, &#39;wb&#39;) as output:
    merger.write(output)

# リソースを解放
pdf1.close()
pdf2.close()
merger.close()</code></pre></div>



<h3 class="wp-block-heading">PDFファイルをページ単位で分割</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import PyPDF2

# 分割するPDFファイルを開く
input_pdf = open(&#39;document.pdf&#39;, &#39;rb&#39;)

# PdfReaderオブジェクトを作成
reader = PyPDF2.PdfReader(input_pdf)

# 分割されたページを新しいPDFファイルとして保存
for i in range(len(reader.pages)):
    writer = PyPDF2.PdfWriter()
    writer.add_page(reader.pages[i])
    
    with open(f&#39;page_{i+1}.pdf&#39;, &#39;wb&#39;) as output_pdf:
        writer.write(output_pdf)

# リソースを解放
input_pdf.close()</code></pre></div>



<h3 class="wp-block-heading">ページの抽出</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import PyPDF2

# 抽出するPDFファイルを開く
input_pdf = open(&#39;document.pdf&#39;, &#39;rb&#39;)

# PdfReaderオブジェクトを作成
reader = PyPDF2.PdfReader(input_pdf)

# 抽出するページ（1ページ目）
page = reader.pages[0]

# 新しいPDFファイルに抽出したページを追加
writer = PyPDF2.PdfWriter()
writer.add_page(page)

# 抽出したページを保存
with open(&#39;extracted_page.pdf&#39;, &#39;wb&#39;) as output_pdf:
    writer.write(output_pdf)

# リソースを解放
input_pdf.close()</code></pre></div>



<h3 class="wp-block-heading">PDFのメタデータを読み取る</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import PyPDF2

# PDFファイルを開く
input_pdf = open(&#39;document.pdf&#39;, &#39;rb&#39;)

# PdfReaderオブジェクトを作成
reader = PyPDF2.PdfReader(input_pdf)

# メタデータを取得
metadata = reader.metadata

# メタデータを表示
print(metadata)

# リソースを解放
input_pdf.close()
</code></pre></div>



<h2 class="wp-block-heading">フォルダー内すべてのPDFを1つに結合</h2>



<p>ユーザーが選択したフォルダー内の<strong>すべてのPDFファイルを結合</strong>し、1つのPDFファイルとして保存します。</p>



<p>Tkinterを使用してフォルダー選択ダイアログを表示し、選択されたフォルダー内のPDFファイルを<strong>PyPDF2のPdfMergerクラス</strong>で結合します。</p>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import os
from PyPDF2 import PdfMerger
from tkinter import Tk, filedialog

# Tkinterを使用してフォルダー選択ダイアログを表示
root = Tk()
root.withdraw()  # メインウィンドウを表示しないようにする
folder_path = filedialog.askdirectory()

if folder_path:
    # フォルダー名を取得
    folder_name = os.path.basename(folder_path)

    # PdfMergerオブジェクトを作成
    merger = PdfMerger()

    # フォルダー内のすべてのPDFファイルを取得し、結合
    for filename in os.listdir(folder_path):
        if filename.endswith(&#39;.pdf&#39;):
            file_path = os.path.join(folder_path, filename)
            merger.append(file_path)

    # 結合されたPDFファイルの保存
    output_path = os.path.join(folder_path, f&#39;{folder_name}.pdf&#39;)
    merger.write(output_path)
    merger.close()

    print(f&quot;結合されたPDFファイルが{output_path}に保存されました。&quot;)
else:
    print(&quot;フォルダーが選択されませんでした。&quot;)
</code></pre></div>



<h4 class="wp-block-heading">UdemyでPythonを学習</h4>



<p><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2F">Udemy</a>は、オンデマンド式の学習講座です。<br>趣味から実務まで使えるおすすめの講座を紹介します。</p>



<div class="wp-block-cocoon-blocks-tab-box-1 blank-box bb-tab bb-pickup block-box has-border-color has-yellow-border-color">
<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython-beginner%2F">現役シリコンバレーエンジニアが教えるPython 3 入門 + 応用 +アメリカのシリコンバレー流コードスタイル</a><br>Pythonをインストールから環境設定、基本文法が学習<br>さらに暗号化、インフラ自動化、非同期処理についても学べます。<br><strong>Pythonを基礎から応用まで学びたい人</strong>におすすめ</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Flearning-ai%2F">みんなのAI講座 ゼロからPythonで学ぶ人工知能と機械学習 【2024年最新版】</a><br>機械学習ライブラリで文字認識や株価分析などを行う。<br><strong>人口知能やニューラルネットワーク、機械学習を学びたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fdatascience365%2F">【世界で55万人が受講】データサイエンティストを目指すあなたへ〜データサイエンス25時間ブートキャンプ〜</a><br>統計分析、機械学習の実装、ディープラーニングの実装を学習。<br><strong>データサイエンティストになりたい人</strong>におすすめ。</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<ul class="wp-block-list">
<li><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fpython_tkinter_master%2F">0から始めるTkinterの使い方完全マスター講座〜Python×GUIの基礎・応用〜</a><br>TkinterのGUIを作成から発展的な操作までアプリ実例を示して学習。<br><strong>アプリ開発したい人</strong>におすすめ。</li>
</ul>
</div>



<h3 class="wp-block-heading">解説</h3>



<ul class="wp-block-list">
<li><strong>モジュール名</strong></li>
</ul>



<p>「os」：ファイルパスの操作やフォルダーのリストを取得します。<br>「PyPDF2」：PDFファイルの読み取りおよび書き込みを行います。<br>「tkinter」：GUIを使用してフォルダー選択ダイアログを表示します。</p>



<p><strong>PyPDFは、標準ライブラリではない</strong>ので、インストール必要があります。<br>コマンドプロンプト（Windows）に入力して、実行します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>pip install PyPDF2</code></pre></div>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「root」：Tkinterのメインウィンドウオブジェクト。GUIダイアログの親ウィンドウとして機能する。<br>「folder_path」：ユーザーが選択したフォルダーのパス。<br>「folder_name」：選択したフォルダーの名前。<br>「merger」：PDFファイルを結合するためのPdfMergerオブジェクト。<br>「output_path」：結合されたPDFファイルの保存先パス。</p>



<ul class="wp-block-list">
<li><strong>それぞれのクラス（関数・メソッド）</strong></li>
</ul>



<p>PdfMergerクラス<br>PDFファイルを結合するためのオブジェクトを提供します。<br>ファイルを追加していき、<strong>最終的に1つのPDFファイルとして出力</strong>します。</p>



<p>Tkクラス<br>Tkinterのメインウィンドウオブジェクトを作成します。<br>GUIアプリケーションの基本ウィンドウとして機能します。</p>



<p>filedialog.askdirectoryメソッド<br>フォルダー選択ダイアログを表示し、<br><strong>ユーザーが選択したフォルダーのパスを取得</strong>します。</p>



<p>os.path.basenameメソッド<br>指定されたパスからフォルダー名を取得します。</p>



<p>os.listdirメソッド<br>指定されたフォルダー内のファイルとサブフォルダーのリストを取得します。</p>



<p>merger.appendメソッド<br>指定されたPDFファイルを結合するために追加します。</p>



<p>merger.writeメソッド<br>結合されたPDFファイルを指定されたパスに保存します。</p>



<p>merger.closeメソッド<br>PdfMergerオブジェクトを閉じてリソースを解放します。</p>



<h3 class="wp-block-heading">実演</h3>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000.webp" alt="" class="wp-image-6694" srcset="https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000.webp 1920w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-300x148.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-1024x504.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-768x378.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-1536x756.webp 1536w" sizes="(max-width: 1920px) 100vw, 1920px" /></figure>



<p>フォルダー選択ダイアログが表示されるので、結合したいPDFファイルが含まれているフォルダーを選択します。</p>



<p>選択されたフォルダー内のすべてのPDFファイルが結合され、新しいPDFファイルとして保存されます。</p>



<h2 class="wp-block-heading">フォルダー内のPDFを1ページずつ分割</h2>



<p>次にユーザーが選択したフォルダー内の<strong>すべてのPDFファイルを各ページごとに分割</strong>し、個別のPDFファイルとして保存します。</p>



<p><strong>フォルダー内の各PDFファイルを読み込み</strong>、それぞれのページを新しいPDFファイルとして保存します。</p>



<h3 class="wp-block-heading">ソースコード</h3>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import os
from PyPDF2 import PdfReader, PdfWriter
from tkinter import Tk, filedialog

# Tkinterを使用してフォルダー選択ダイアログを表示
root = Tk()
root.withdraw()  # メインウィンドウを表示しないようにする
folder_path = filedialog.askdirectory()

if folder_path:
    # 出力用のフォルダーを作成
    output_folder = os.path.join(folder_path, &#39;split_pages&#39;)
    os.makedirs(output_folder, exist_ok=True)

    # フォルダー内のすべてのPDFファイルを処理
    for filename in os.listdir(folder_path):
        if filename.endswith(&#39;.pdf&#39;):
            file_path = os.path.join(folder_path, filename)
            pdf = PdfReader(file_path)

            # 各ページを個別のPDFファイルとして保存
            for page_num in range(len(pdf.pages)):
                pdf_writer = PdfWriter()
                pdf_writer.add_page(pdf.pages[page_num])

                # 新しいPDFファイル名を作成
                output_filename = os.path.join(output_folder, f&#39;{os.path.splitext(filename)[0]}_page_{page_num + 1}.pdf&#39;)
                with open(output_filename, &#39;wb&#39;) as output_pdf:
                    pdf_writer.write(output_pdf)

    print(f&quot;分割されたPDFファイルが{output_folder}に保存されました。&quot;)
else:
    print(&quot;フォルダーが選択されませんでした。&quot;)
</code></pre></div>



<h3 class="wp-block-heading">解説</h3>



<p><strong>上記と同じモジュールとフィールドは省略します。</strong></p>



<ul class="wp-block-list">
<li><strong>フィールド（メンバ変数）</strong></li>
</ul>



<p>「filename」：現在処理中のPDFファイルの名前。<br>「file_path」：現在処理中のPDFファイルのフルパス。<br>「pdf」：現在読み込まれているPDFファイルのPdfReaderオブジェクト。<br>「page_num」：現在処理中のページ番号。<br>「pdf_writer」：新しいPDFファイルを作成するためのPdfWriterオブジェクト。<br>「output_filename」：分割された各ページのPDFファイル名。</p>



<ul class="wp-block-list">
<li><strong>それぞれのクラス（関数・メソッド）</strong></li>
</ul>



<p>PdfReaderクラス<br>PDFファイルを読み取るためのオブジェクトを提供します。<br><strong>PDFファイルを開いてページごとの情報にアクセス</strong>できます。</p>



<p>PdfWriterクラス<br>PDFファイルを作成するためのオブジェクトを提供します。<br><strong>ページを追加して新しいPDFファイルとして保存</strong>します。</p>



<p>os.path.joinメソッド<br>複数のパスコンポーネントを結合して<strong>1つのパスを作成</strong>します。</p>



<p>os.makedirsメソッド<br>指定されたパスにディレクトリを作成します。<br><strong>exist_ok=Trueオプション</strong>を指定することで、すでに存在する場合でもエラーを発生させません。</p>



<p>os.listdirメソッド<br>指定されたフォルダー内のファイルとサブフォルダーのリストを取得します。</p>



<p>pdf_writer.add_pageメソッド<br>PdfWriterオブジェクトにページを追加します。</p>



<p>pdf_writer.writeメソッド<br>PdfWriterオブジェクトの内容を指定されたファイルに書き込みます。</p>



<p>os.path.splitextメソッド<br>ファイル名と拡張子を分割します。</p>



<h3 class="wp-block-heading">実演</h3>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000.webp" alt="" class="wp-image-6695" srcset="https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000.webp 1920w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-300x148.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-1024x504.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-768x378.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-1536x756.webp 1536w" sizes="(max-width: 1920px) 100vw, 1920px" /></figure>



<p>フォルダー選択ダイアログが表示されるので、分割したいPDFファイルが含まれているフォルダーを選択します。</p>



<p>選択されたフォルダー内のすべてのPDFファイルがページごとに分割され、新しいPDFファイルとして保存されます。</p>



<h2 class="wp-block-heading">まとめ</h2>



<p>この記事では、Pythonを使ってPDFファイルを結合および分割する方法を紹介しました。<br>PyPDF2ライブラリを使用することで、これらの操作を簡単に実行できます。</p>



<p>業務効率化や資料管理の向上に有効となります。</p>



<div class="wp-block-cocoon-blocks-micro-balloon-2 aligncenter micro-balloon micro-top mc-circle micro-copy"><span class="micro-balloon-content micro-content"><strong>Udemyで学習する</strong></span></div>



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/pypdf-edit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
