<?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=7.0</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>
<div class="label-box-content block-box-content box-content">
<p class="wp-block-paragraph">Pythonで進捗バーを表示する。</p>



<figure class="wp-block-image size-full"><figure id="attachment_mmd_8842" class="wp-block-image "><img decoding="async" width="1280" height="720" src="https://alicia-ing.com/wp-content/uploads/2026/06/complete.gif" class="attachment-full size-full" alt="実行例" loading="lazy" /></figure></figure>
</div>


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


<p class="wp-block-paragraph">本記事では、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>
<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 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"><figure id="attachment_mmd_8268" class="wp-block-image "><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/12/tqdm.webp" class="attachment-full size-full" alt="tqdmについて" loading="lazy" /></figure></figure>


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


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


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


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


<p class="wp-block-paragraph">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 class="wp-block-paragraph">基本的な使い方としては、<strong>forループにtqdmを追加するだけ</strong>で、<br>簡単に進捗バーを表示することができます。</p>


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


<p class="wp-block-paragraph">また、進捗をリアルタイムで確認できるため、<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 class="wp-block-paragraph">このコードでは、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 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 class="wp-block-paragraph"><strong>descを使って処理内容を説明</strong>することで、<br>何をしているのかをユーザーにわかりやすく伝えることができます。</p>


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


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8269" class="wp-block-image "><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/12/completion-rate.webp" class="attachment-full size-full" alt="完了率表示" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">処理は、フォルダ内のファイルを順次ループし、<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 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 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 class="wp-block-paragraph">その際、<strong>tqdmを用いて進捗状況を一歩ずつ表示し、処理の完了までの時間を視覚化</strong>しています。</p>


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


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


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


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


<p class="wp-block-paragraph">「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 class="wp-block-paragraph">「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 class="wp-block-paragraph">この関数は、指定されたフォルダ内の画像ファイルをWebP形式に変換する処理を行います。</p>


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


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


<p class="wp-block-paragraph"><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(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]

    # ファイル数が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] + '.webp')

        # 画像を開いてWebP形式で保存する
        try:
            with Image.open(input_path) as image:
                image.save(output_path, 'webp')
        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 = 'Input'
output_folder = 'Output'

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


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



<p class="wp-block-paragraph"><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 class="wp-block-paragraph">プログラムを実行すると、冒頭で示したような進捗バーが表示されます。</p>


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


<p class="wp-block-paragraph">必要に応じて、プログレスバーを導入してください。</p>


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


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


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


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


<p class="wp-block-paragraph">次回の開発では、さらに複雑な処理にもこの進捗表示を実装して、便利さを向上させていきましょう。</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>
<div class="label-box-content block-box-content box-content">
<p class="wp-block-paragraph">Google Text-to-SpeechをPythonから制御する。</p>



<figure class="wp-block-image size-full"><figure id="attachment_mmd_8625" class="wp-block-image "><img decoding="async" width="1920" height="940" src="https://alicia-ing.com/wp-content/uploads/2025/03/complete-1.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>
</div>


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


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


<p class="wp-block-paragraph">また、商用利用や料金、音声ファイルの保存方法など、<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>
<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 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"><figure id="attachment_mmd_8223" class="wp-block-image "><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech-1.webp" class="attachment-full size-full" alt="Text-to-Speechについて" loading="lazy" /></figure></figure>


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


<p class="wp-block-paragraph">作成した動画にナレーションを入れたい場合、<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"><figure id="attachment_mmd_8224" class="wp-block-image "><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/how_to_register.webp" class="attachment-full size-full" alt="アカウント作成について" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">Cloud Speech-to-Textを有効にして、APIを取得します。</p>


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


<p class="wp-block-paragraph">「<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"><figure id="attachment_mmd_8205" class="wp-block-image "><img decoding="async" width="1879" height="953" src="https://alicia-ing.com/wp-content/uploads/2024/11/register_account.webp" class="attachment-full size-full" alt="アカウント作成" loading="lazy" /></figure></figure>


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


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


<figure class="wp-block-image aligncenter size-full"><figure id="attachment_mmd_8206" class="wp-block-image "><img decoding="async" width="1884" height="1064" src="https://alicia-ing.com/wp-content/uploads/2024/11/register_card.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


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


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


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8208" class="wp-block-image "><img decoding="async" width="1884" height="934" src="https://alicia-ing.com/wp-content/uploads/2024/11/library.webp" class="attachment-full size-full" alt="ライブラリの場所" loading="lazy" /></figure></figure>


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


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8209" class="wp-block-image "><img decoding="async" width="1884" height="875" src="https://alicia-ing.com/wp-content/uploads/2024/11/Text-to-Speech.webp" class="attachment-full size-full" alt="APIを有効" loading="lazy" /></figure></figure>


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


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


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8210" class="wp-block-image "><img decoding="async" width="1468" height="1080" src="https://alicia-ing.com/wp-content/uploads/2024/11/service_account.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">そのほかの情報は<strong>省略可能</strong>ですので、そのままで大丈夫です。</p>


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8211" class="wp-block-image "><img decoding="async" width="1835" height="1080" src="https://alicia-ing.com/wp-content/uploads/2024/11/account_detail.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8212" class="wp-block-image "><img decoding="async" width="1558" height="1027" src="https://alicia-ing.com/wp-content/uploads/2024/11/make_key.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8213" class="wp-block-image "><img decoding="async" width="1920" height="1080" src="https://alicia-ing.com/wp-content/uploads/2024/11/JSON_API.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">このファイルを適切に管理することで、安全に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"><figure id="attachment_mmd_8225" class="wp-block-image "><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/operation.webp" class="attachment-full size-full" alt="Pythonで動かすには" loading="lazy" /></figure></figure>


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


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


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


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


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


<p class="wp-block-paragraph">また、教育機関での学習用資料の作成や、<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['GOOGLE_APPLICATION_CREDENTIALS'] = 'key.json'

# 音声生成関数
def generate_audio(csv_path):
    # 保存先ディレクトリをCSVファイルと同じ場所に設定
    save_directory = os.path.dirname(csv_path)

    # Google Cloud TTSクライアントの作成
    client = texttospeech.TextToSpeechClient()

    # CSVファイルの読み込み
    with open(csv_path, 'r', newline='', encoding='utf-8') 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'{index+1}_{word}.wav')

                # 音声データの保存
                with open(filename, 'wb') as out:
                    out.write(response.audio_content)
                    print(f'Saved: {filename}')

# メイン処理
if __name__ == &quot;__main__&quot;:
    # CSVファイルのパスを指定
    csv_path = 'voice.csv'

    # ファイルが存在するか確認
    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 class="wp-block-paragraph"><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 class="wp-block-paragraph">「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 class="wp-block-paragraph">「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 class="wp-block-paragraph"><strong>generate_audioクラス</strong></p>


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


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


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


<p class="wp-block-paragraph">本ソースコードでは、「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 class="wp-block-paragraph">スクリプトを実行すると、csv（voice.csv）にのA列にあるテキストを読み込み、<br>wav形式で保存します。</p>


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8226" class="wp-block-image "><img decoding="async" width="683" height="333" src="https://alicia-ing.com/wp-content/uploads/2024/11/csv_data.webp" class="attachment-full size-full" alt="csvデータ" loading="lazy" /></figure></figure>


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


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


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


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


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


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


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


<p class="wp-block-paragraph">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 class="wp-block-paragraph">PythonのライブラリであるMoviePyを使えば、<br>動画編集が簡単に自動化できます。</p>


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


<p class="wp-block-paragraph">本記事では、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>
<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 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"><figure id="attachment_mmd_8158" class="wp-block-image "><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/movie.webp" class="attachment-full size-full" alt="moviepyについて" loading="lazy" /></figure></figure>


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


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


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


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_8159" class="wp-block-image "><img decoding="async" width="1200" height="630" src="https://alicia-ing.com/wp-content/uploads/2024/11/basic-function.webp" class="attachment-full size-full" alt="基本機能について" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">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>
<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>


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


<p class="wp-block-paragraph">動画の特定の部分を切り取ることで、必要なシーンだけを抽出できます。</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 class="wp-block-paragraph">input_video.mp4の10秒から30秒までの部分を切り取って、<br>新しい動画ファイルとして保存します。</p>


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


<p class="wp-block-paragraph">複数の動画を連結して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 class="wp-block-paragraph">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"><figure id="attachment_mmd_1797" class="wp-block-image "><img decoding="async" width="512" height="512" src="https://alicia-ing.com/wp-content/uploads/2023/05/cropped-alicia.webp" class="attachment-full size-full" alt="筆者" loading="lazy" /></figure></figure>
<div class="speech-name">筆者</div></div>
<div class="speech-balloon">
<p class="wp-block-paragraph">最近のYouTubeは、総集編が多いので、<br>これで自動編集ができる！</p>
</div></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>
<div class="label-box-content block-box-content box-content">
<p class="wp-block-paragraph">顔にランドマーク（3Dマスク）を付ける。</p>



<figure class="wp-block-image size-full"><figure id="attachment_mmd_7303" class="wp-block-image "><img decoding="async" width="1024" height="512" src="https://alicia-ing.com/wp-content/uploads/2024/10/complete-1.webp" class="attachment-full size-full" alt="顔のランドマーク検出" loading="lazy" /></figure></figure>



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


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


<p class="wp-block-paragraph">本記事では、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>
<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 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 class="wp-block-paragraph">CMakeは、クロスプラットフォームのビルドシステムで、<br>ソースコードのコンパイルやビルドの自動化を行うツールです。</p>


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


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


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


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


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


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


<p class="wp-block-paragraph"></p>


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


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


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


<p class="wp-block-paragraph">これにより、顔の特徴を捉えた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['chin'])], isClosed=False, color=(0, 255, 0), thickness=2)

        # 眉毛
        cv2.polylines(image, [np.array(face_landmarks['left_eyebrow'])], isClosed=False, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks['right_eyebrow'])], isClosed=False, color=(0, 255, 0), thickness=2)

        # 鼻
        cv2.polylines(image, [np.array(face_landmarks['nose_bridge'])], isClosed=False, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks['nose_tip'])], isClosed=False, color=(0, 255, 0), thickness=2)

        # 目
        cv2.polylines(image, [np.array(face_landmarks['left_eye'])], isClosed=True, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks['right_eye'])], isClosed=True, color=(0, 255, 0), thickness=2)

        # 口
        cv2.polylines(image, [np.array(face_landmarks['top_lip'])], isClosed=True, color=(0, 255, 0), thickness=2)
        cv2.polylines(image, [np.array(face_landmarks['bottom_lip'])], 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 class="wp-block-paragraph"><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 class="wp-block-paragraph">「cv2」：OpenCVを使用して画像の読み込み、処理、保存を行うために使用。画像にランドマークを描画する際にも利用される。<br>「face_recognition」：顔のランドマーク（顎、眉毛、目、鼻、口など）を検出するために使用。<br>「numpy」：顔のランドマークの座標を配列に変換し、cv2.polylinesで使用するために利用。<br>「tkinter.filedialog」：ファイル選択ダイアログを使用して、画像ファイルを選択するために使用。<br>「os」：ファイルのパスを操作し、新しいファイルの保存先や名前を設定するために使用。</p>


<p class="wp-block-paragraph">「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 class="wp-block-paragraph">「image_path」：ユーザーが選択した画像のファイルパスを保存する変数。<br>select_image()関数で取得され、apply_3d_mask()関数で使用される。</p>


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


<p class="wp-block-paragraph">ユーザーがファイル選択ダイアログを使用して画像ファイルを選択する</p>


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


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


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


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


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


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


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


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


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


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


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


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


<p class="wp-block-paragraph">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>
<div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-full"><figure id="attachment_mmd_7273" class="wp-block-image "><img decoding="async" width="1280" height="720" src="https://alicia-ing.com/wp-content/uploads/2023/02/complete-3.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>
</div>


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


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


<p class="wp-block-paragraph">本記事では、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>
<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 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 class="wp-block-paragraph">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"><figure id="attachment_mmd_7059" class="wp-block-image "><img decoding="async" width="1024" height="390" src="https://alicia-ing.com/wp-content/uploads/2024/09/window-1-1024x390.webp" class="attachment-1024x390 size-1024x390" alt="" loading="lazy" /></figure></figure>


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


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


<p class="wp-block-paragraph">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"><figure id="attachment_mmd_7060" class="wp-block-image "><img decoding="async" width="929" height="431" src="https://alicia-ing.com/wp-content/uploads/2024/09/Slider.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">スライダーバーは、<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>
<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>


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


<p class="wp-block-paragraph">スライダーバーには初期値を設定できます。<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"><figure id="attachment_mmd_7061" class="wp-block-image "><img decoding="async" width="1024" height="538" src="https://alicia-ing.com/wp-content/uploads/2024/09/set-1024x538.webp" class="attachment-1024x538 size-1024x538" alt="" loading="lazy" /></figure></figure>


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


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


<p class="wp-block-paragraph">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"><figure id="attachment_mmd_7062" class="wp-block-image "><img decoding="async" width="1024" height="374" src="https://alicia-ing.com/wp-content/uploads/2024/09/option-1-1024x374.webp" class="attachment-1024x374 size-1024x374" alt="" loading="lazy" /></figure></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>
<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>


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


<figure class="wp-block-image size-large"><figure id="attachment_mmd_7064" class="wp-block-image "><img decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/graph-1-1024x528.webp" class="attachment-1024x528 size-1024x528" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">インストールには、それぞれ<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 class="wp-block-paragraph">数値解析には、様々なライブラリがあります。</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 class="wp-block-paragraph">「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 class="wp-block-paragraph">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 class="wp-block-paragraph">スクリプトの主要な機能は、<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 class="wp-block-paragraph">スライダーを使ったリアルタイムグラフ操作や色の動的変更などを通して、<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>
<div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-full"><figure id="attachment_mmd_8587" class="wp-block-image "><img decoding="async" width="1920" height="940" src="https://alicia-ing.com/wp-content/uploads/2022/12/complete-2.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>
</div>


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


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


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


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


<p class="wp-block-paragraph">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"><figure id="attachment_mmd_7034" class="wp-block-image "><img decoding="async" width="935" height="390" src="https://alicia-ing.com/wp-content/uploads/2024/09/window.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">リストボックスは、<strong>Listboxクラス</strong>を使って作成します。</p>


<p class="wp-block-paragraph">ユーザーが複数の項目から選択できるウィジェットで、ファイル選択やオプションの選択画面などに幅広く使われます。</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"><figure id="attachment_mmd_7035" class="wp-block-image "><img decoding="async" width="1024" height="389" src="https://alicia-ing.com/wp-content/uploads/2024/09/list-box-1024x389.webp" class="attachment-1024x389 size-1024x389" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">リストボックスは、次のような用途に適しています。</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>
<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>


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


<p class="wp-block-paragraph">リストボックスから値を取得したり、項目を削除・選択することもできます。</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 class="wp-block-paragraph">リスト項目を用意して、これらをリストボックスに入れれば、追加できます。<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"><figure id="attachment_mmd_7036" class="wp-block-image "><img decoding="async" width="1024" height="408" src="https://alicia-ing.com/wp-content/uploads/2024/09/insert-list-1024x408.webp" class="attachment-1024x408 size-1024x408" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">リストボックス（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"><figure id="attachment_mmd_7037" class="wp-block-image "><img decoding="async" width="1920" height="944" src="https://alicia-ing.com/wp-content/uploads/2024/09/scroll-bar.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


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


<p class="wp-block-paragraph">リストボックスもボタンやラベルのようにさまざまなオプションを設定できます。</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>
<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 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"><figure id="attachment_mmd_7038" class="wp-block-image "><img decoding="async" width="1024" height="445" src="https://alicia-ing.com/wp-content/uploads/2024/09/option-1024x445.webp" class="attachment-1024x445 size-1024x445" alt="" loading="lazy" /></figure></figure>


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


<figure class="wp-block-image size-large"><figure id="attachment_mmd_7039" class="wp-block-image "><img decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/add-list-1024x528.webp" class="attachment-1024x528 size-1024x528" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">エントリーボックスにユーザーが文字を入力し、<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 class="wp-block-paragraph">また、リストボックスにスクロールバーを追加して、<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 class="wp-block-paragraph">ダブルクリックをするには、<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 class="wp-block-paragraph"><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 class="wp-block-paragraph">「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 class="wp-block-paragraph"><strong>add_listbox関数</strong><br>この関数は、エントリーに入力された文字列を取得し、リストボックスに追加します。<br>入力が空白でない場合のみ、エントリーから文字列を取得し、<br>それをリストボックスの最後に追加します。</p>


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


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


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


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


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


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


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


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


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


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


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


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


<p class="wp-block-paragraph">オプションを活用して、デザインや操作性を調整し、より高品質な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>
<div class="label-box-content block-box-content box-content">
<p class="wp-block-paragraph">ラジオボタンの選択でラベルの表示・非表示にして、文字、色を変更する。</p>



<figure class="wp-block-image size-full"><figure id="attachment_mmd_8625" class="wp-block-image "><img decoding="async" width="1920" height="940" src="https://alicia-ing.com/wp-content/uploads/2025/03/complete-1.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>
</div>


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


<p class="wp-block-paragraph">本記事では、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>
<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 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 class="wp-block-paragraph">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"><figure id="attachment_mmd_6997" class="wp-block-image "><img decoding="async" width="1024" height="343" src="https://alicia-ing.com/wp-content/uploads/2024/09/widget-1024x343.webp" class="attachment-1024x343 size-1024x343" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">これがユーザーとのインターフェースの基盤となる部分です。</p>


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


<p class="wp-block-paragraph">ラジオボタンは、<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"><figure id="attachment_mmd_6998" class="wp-block-image "><img decoding="async" width="1024" height="337" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio_button-1024x337.webp" class="attachment-1024x337 size-1024x337" alt="" loading="lazy" /></figure></figure>


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


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


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


<p class="wp-block-paragraph">ラジオボタンの用途は、多岐に広がり使用することでユーザビリティの向上につながります。</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>
<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>


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


<p class="wp-block-paragraph">ラジオボタンを使用する際、<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"><figure id="attachment_mmd_6999" class="wp-block-image "><img decoding="async" width="1024" height="462" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio-option-1024x462.webp" class="attachment-1024x462 size-1024x462" alt="" loading="lazy" /></figure></figure>


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


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


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


<p class="wp-block-paragraph">これにより、選択肢が直感的に分かりやすくなります。</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='w')  # 左寄せで配置</code></pre></div>


<figure class="wp-block-image size-large"><figure id="attachment_mmd_7000" class="wp-block-image "><img decoding="async" width="1024" height="298" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio-vertical-1024x298.webp" class="attachment-1024x298 size-1024x298" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">配置には、<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>
<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>


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


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


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


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


<figure class="wp-block-image size-large"><figure id="attachment_mmd_7001" class="wp-block-image "><img decoding="async" width="1024" height="311" src="https://alicia-ing.com/wp-content/uploads/2024/09/radio-side-1024x311.webp" class="attachment-1024x311 size-1024x311" alt="" loading="lazy" /></figure></figure>


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


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


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


<p class="wp-block-paragraph">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 class="wp-block-paragraph">例えば、<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"><figure id="attachment_mmd_7002" class="wp-block-image "><img decoding="async" width="1920" height="950" src="https://alicia-ing.com/wp-content/uploads/2024/09/default_color.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


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


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


<p class="wp-block-paragraph">これにより、ラジオボタンがクリックされたときに自動的に指定された関数が呼び出され、イベント処理が追加されます。</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"><figure id="attachment_mmd_7003" class="wp-block-image "><img decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/value-update-1024x528.webp" class="attachment-1024x528 size-1024x528" alt="" loading="lazy" /></figure></figure>


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


<p class="wp-block-paragraph">また、特定の選択肢でラベルを非表示にすることも可能です。</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='w', 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 class="wp-block-paragraph"><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 class="wp-block-paragraph">「tkinter」：インストールは不要で、Pythonに標準で付属しているためすぐに使用可能です。</p>


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


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


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


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


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


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


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


<p class="wp-block-paragraph">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>
<div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-full"><figure id="attachment_mmd_8842" class="wp-block-image "><img decoding="async" width="1280" height="720" src="https://alicia-ing.com/wp-content/uploads/2026/06/complete.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>
</div>


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


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


<p class="wp-block-paragraph">この記事では、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>
<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 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 class="wp-block-paragraph">Tkinterを使ったGUIアプリケーションは、最初に画面、つまりウィンドウを作成するところから始まります。</p>


<p class="wp-block-paragraph">このウィンドウがユーザーとの対話の場となり、その上にボタンやエントリーボックスなどのウィジェットを配置していきます。</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"><figure id="attachment_mmd_6957" class="wp-block-image "><img decoding="async" width="1024" height="380" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1024x380.webp" class="attachment-1024x380 size-1024x380" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">ウィンドウサイズの設定やタイトルの指定など、<br>ユーザーにとって使いやすいデザインを作ることができます。</p>


<h2 class="wp-block-heading">エントリー(Entry)作成</h2>


<p class="wp-block-paragraph">エントリーウィジェットは、ユーザーが文字を入力するための入力フィールドです。<br>Tkinterでは、Entryクラスを使って簡単に作成できます。</p>


<p class="wp-block-paragraph">ここでは、エントリーボックスをウィンドウに配置、サイズや位置を調整する方法を見ていきます。</p>


<h3 class="wp-block-heading">Pack()</h3>


<p class="wp-block-paragraph">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"><figure id="attachment_mmd_6958" class="wp-block-image "><img decoding="async" width="1024" height="380" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-1024x380.webp" class="attachment-1024x380 size-1024x380" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">ウィジェットを上から順番に詰め込むように配置したい場合に使います。</p>


<h3 class="wp-block-heading">grid()</h3>


<p class="wp-block-paragraph">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"><figure id="attachment_mmd_6959" class="wp-block-image "><img decoding="async" width="1024" height="350" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-1024x350.webp" class="attachment-1024x350 size-1024x350" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">より柔軟なレイアウトが可能で、複数のウィジェットを整理して配置したい場合に適しています。</p>


<h3 class="wp-block-heading">Place()</h3>


<p class="wp-block-paragraph">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"><figure id="attachment_mmd_6961" class="wp-block-image "><img decoding="async" width="1006" height="410" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-place.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">ウィンドウ上の特定の位置にウィジェットを置く必要がある場合に便利です。</p>


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


<p class="wp-block-paragraph">Tkinterのエントリーボックスは、色、フォント、サイズなどをカスタマイズできます。<br>例えば、入力フィールドの背景色を変更したり、フォントの種類やサイズを指定することが可能です。</p>


<figure class="wp-block-image size-large"><figure id="attachment_mmd_6962" class="wp-block-image "><img decoding="async" width="1024" height="315" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-1024x315.webp" class="attachment-1024x315 size-1024x315" alt="" loading="lazy" /></figure></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 class="wp-block-paragraph">エントリーボックスに入力された文字列を取得するには、get()メソッドを使います。<br>また、insert()メソッドで初期値を設定したり、delete()メソッドで入力をクリアすることも可能です。</p>


<figure class="wp-block-image size-large"><figure id="attachment_mmd_6963" class="wp-block-image "><img decoding="async" width="1024" height="426" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-1024x426.webp" class="attachment-1024x426 size-1024x426" alt="" loading="lazy" /></figure></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 class="wp-block-paragraph">さらに改良をして、ボタンを押すと、テキストを取得し、エントリーの文字を削除するようにします。</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"><figure id="attachment_mmd_6966" class="wp-block-image "><img decoding="async" width="1920" height="944" src="https://alicia-ing.com/wp-content/uploads/2024/09/get.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">ユーザーにとって使いやすいインターフェースを作ることができます。</p>


<h2 class="wp-block-heading">入力値をリアルタイムで表示</h2>


<p class="wp-block-paragraph">ユーザーがエントリーボックスに入力した内容を<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 class="wp-block-paragraph">traceメソッドを使って、入力が変更されるたびに反応する仕組みを作ることができます。</p>


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


<p class="wp-block-paragraph">print()をラベルに変更して、Tkinter上に表示させることも可能です。</p>


<h2 class="wp-block-heading">Enter(Return)キーで入力値を取得</h2>


<p class="wp-block-paragraph">ユーザーが入力を終えた後、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 class="wp-block-paragraph">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 class="wp-block-paragraph">これにより、フォーム送信や次の処理に進む操作を自然な形で実現できます。</p>


<h2 class="wp-block-heading">Pythonでログインフォームを作成する</h2>


<figure class="wp-block-image size-large"><figure id="attachment_mmd_6969" class="wp-block-image "><img decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/login-1024x528.webp" class="attachment-1024x528 size-1024x528" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">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>
<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 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'[A-Z]', password) and  # 大文字
        re.search(r'[a-z]', password) and  # 小文字
        re.search(r'[\W_]', 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 class="wp-block-paragraph"><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 class="wp-block-paragraph">「tkinter」：Pythonの標準ライブラリで、GUIアプリケーションを作成するために使用。「tkinter.messagebox」：GUIアプリケーション内で情報やエラーメッセージを表示するダイアログボックスを提供する。<br>「re」：正規表現を利用した文字列のパターンマッチングを行うために使用。パスワードのバリデーションに活用されている。</p>


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


<p class="wp-block-paragraph">「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 class="wp-block-paragraph">「validate_password」関数<br>正規表現を使用して、入力されたパスワードが大文字、小文字、記号を含むかをチェックし、条件を満たす場合にTrueを返す。それ以外の場合はFalseを返す。</p>


<p class="wp-block-paragraph">「login」関数<br>処理の説明を文章にする。<br>ユーザーが入力したユーザー名とパスワードを検証する。入力が空の場合や不正な組み合わせの場合には、エラーメッセージを表示する。正しいユーザー名とパスワードが入力された場合は、画面Bに遷移する。</p>


<p class="wp-block-paragraph">「open_screen_b」関数<br>画面Aを非表示にして、新しいウィンドウ（画面B）を表示し、ユーザーに挨拶メッセージと新しいパスワードを入力させる。パスワード変更のための処理もこの関数内で行われる。</p>


<p class="wp-block-paragraph">「change_password」関数<br>ユーザーが入力した新しいパスワードが「validate_password」で有効かを確認し、有効な場合は現在のパスワードを更新し、画面Bを閉じて画面Aを再表示する。無効な場合はエラーメッセージを表示する。</p>


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


<p class="wp-block-paragraph">ログイン画面が表示されて、ユーザーが入力した情報に基づいて次の画面に遷移する処理を行います。</p>


<p class="wp-block-paragraph">エントリーウィジェットにユーザー名とパスワードを入力し、それを検証します。<br>もし正しいユーザー名とパスワードが入力されると、次の画面が表示され、<br>パスワードを変更できるようになります。</p>


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


<p class="wp-block-paragraph">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>
<div class="label-box-content block-box-content box-content">
<figure class="wp-block-image size-large"><figure id="attachment_mmd_7207" class="wp-block-image "><img decoding="async" width="1024" height="504" src="https://alicia-ing.com/wp-content/uploads/2024/10/complete.webp" class="attachment-1024x729 size-1024x729" alt="" loading="lazy" /></figure></figure>
</div>


<p class="wp-block-paragraph">Pythonでテキストを音声として読み上げたいときには、<br>オフラインで動作する合成音声ライブラリ「<strong>pyttsx3</strong>」を使うと便利です。</p>


<p class="wp-block-paragraph">このライブラリは、簡単にテキストを音声に変換でき、速度や音声の種類も調整可能です。<br>プログラムにナレーションを追加したり、読み上げアプリを開発したりする際に活躍します。</p>


<p class="wp-block-paragraph">本記事では、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>
<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 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"><figure id="attachment_mmd_6917" class="wp-block-image "><img decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/pyttsx3-1024x528.webp" class="attachment-1024x528 size-1024x528" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">pyttsx3は、Python用のテキスト読み上げライブラリで、<br><strong>コンピュータのローカルで音声合成</strong>を行います。</p>


<p class="wp-block-paragraph">インストールは、<strong>コマンドプロンプト、ターミナル</strong>でできます。</p>


<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>pip install pyttsx3</code></pre></div>


<p class="wp-block-paragraph">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 class="wp-block-paragraph">また、音声速度や音量、性別の調整が可能で、カスタマイズ性が高い点も特徴です。</p>


<h3 class="wp-block-heading">音声の読み上げ</h3>


<p class="wp-block-paragraph">テキストを<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 class="wp-block-paragraph">音声の再生速度、音量、音声の性別など、<strong>細かいプロパティを変更</strong>できます。<br>カスタマイズした音声合成が可能です。</p>


<p class="wp-block-paragraph">速度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('volume', 0.9)

# 速度（WPM: words per minute）
engine.setProperty('rate', 150)

# 音声（性別）の変更
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)  # 男性の声
#engine.setProperty('voice', voices[1].id)  # 女性の声

engine.say(&quot;Hello alicia-ing&quot;)
engine.runAndWait()</code></pre></div>


<h3 class="wp-block-heading">音声の保存</h3>


<p class="wp-block-paragraph">テキストを音声ファイル（WAV形式）として保存することができます。<br><strong>save_to_file()メソッドを使用</strong>して、音声をファイルに書き出すことが可能です。</p>


<p class="wp-block-paragraph">ただし、<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 , 'voice.wav')</code></pre></div>


<h3 class="wp-block-heading">イベント制御</h3>


<p class="wp-block-paragraph"><strong>読み上げ開始、終了時にイベントをトリガー</strong>にして、プログラムを処理する。</p>


<p class="wp-block-paragraph">再生が開始したら、「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('started-utterance', lambda name: onStart(&quot;Alicia&quot;))
engine.connect('finished-utterance', 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"><figure id="attachment_mmd_6918" class="wp-block-image "><img decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/commercial-use-1-1024x528.webp" class="attachment-1024x528 size-1024x528" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">pyttsx3はオープンソースライブラリであり、商用利用も可能です。</p>


<p class="wp-block-paragraph">ただし、音声エンジンに依存する部分もあるため、<br><strong>合成音声エンジン自体のライセンス条件を確認</strong>する必要があります。</p>


<p class="wp-block-paragraph">そのため、商用利用可能な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"><figure id="attachment_mmd_6919" class="wp-block-image "><img decoding="async" width="1024" height="528" src="https://alicia-ing.com/wp-content/uploads/2024/09/language-1024x528.webp" class="attachment-1024x528 size-1024x528" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">pyttsx3は、使用する音声エンジンに依存して、様々な言語に対応しています。<br>具体的には、英語、日本語、フランス語、ドイツ語など、多くの言語で音声合成が可能です。</p>


<p class="wp-block-paragraph">ただし、エンジンや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"><figure id="attachment_mmd_1797" class="wp-block-image "><img decoding="async" width="512" height="512" src="https://alicia-ing.com/wp-content/uploads/2023/05/cropped-alicia.webp" class="attachment-full size-full" alt="筆者" loading="lazy" /></figure></figure>
<div class="speech-name">筆者</div></div>
<div class="speech-balloon">
<p class="wp-block-paragraph"><strong>Windowsでは、英語、日本語、フランス語</strong>はできた。ドイツ語もできたが英語？ってなった。<br>韓国語は発音できず、中国語は違う気がした。</p>
</div></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>
<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"><figure id="attachment_mmd_6692" class="wp-block-image "><img decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/merger_pdf.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>



<ul class="wp-block-list">
<li>PDFを１ページずつ分割する。</li>
</ul>



<figure class="wp-block-image size-full"><figure id="attachment_mmd_6693" class="wp-block-image "><img decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/splitpdf.gif" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>
</div>


<p class="wp-block-paragraph">Pythonを使えば、<strong>複数のPDFファイルを1つに結合</strong>とPDFファイルを１つずつ分割することが簡単にできます。</p>


<p class="wp-block-paragraph">本記事では、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>
<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 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 class="wp-block-paragraph">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>
<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>


<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('document1.pdf', 'rb')
pdf2 = open('document2.pdf', 'rb')

# PdfMergerオブジェクトを作成
merger = PyPDF2.PdfMerger()

# PDFファイルを追加
merger.append(pdf1)
merger.append(pdf2)

# 結合されたPDFをファイルとして書き出し
with open('new_document.pdf', 'wb') 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('document.pdf', 'rb')

# 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'page_{i+1}.pdf', 'wb') 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('document.pdf', 'rb')

# PdfReaderオブジェクトを作成
reader = PyPDF2.PdfReader(input_pdf)

# 抽出するページ（1ページ目）
page = reader.pages[0]

# 新しいPDFファイルに抽出したページを追加
writer = PyPDF2.PdfWriter()
writer.add_page(page)

# 抽出したページを保存
with open('extracted_page.pdf', 'wb') 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('document.pdf', 'rb')

# 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 class="wp-block-paragraph">ユーザーが選択したフォルダー内の<strong>すべてのPDFファイルを結合</strong>し、1つのPDFファイルとして保存します。</p>


<p class="wp-block-paragraph">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('.pdf'):
            file_path = os.path.join(folder_path, filename)
            merger.append(file_path)

    # 結合されたPDFファイルの保存
    output_path = os.path.join(folder_path, f'{folder_name}.pdf')
    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 class="wp-block-paragraph"><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 class="wp-block-paragraph">「os」：ファイルパスの操作やフォルダーのリストを取得します。<br>「PyPDF2」：PDFファイルの読み取りおよび書き込みを行います。<br>「tkinter」：GUIを使用してフォルダー選択ダイアログを表示します。</p>


<p class="wp-block-paragraph"><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 class="wp-block-paragraph">「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 class="wp-block-paragraph">PdfMergerクラス<br>PDFファイルを結合するためのオブジェクトを提供します。<br>ファイルを追加していき、<strong>最終的に1つのPDFファイルとして出力</strong>します。</p>


<p class="wp-block-paragraph">Tkクラス<br>Tkinterのメインウィンドウオブジェクトを作成します。<br>GUIアプリケーションの基本ウィンドウとして機能します。</p>


<p class="wp-block-paragraph">filedialog.askdirectoryメソッド<br>フォルダー選択ダイアログを表示し、<br><strong>ユーザーが選択したフォルダーのパスを取得</strong>します。</p>


<p class="wp-block-paragraph">os.path.basenameメソッド<br>指定されたパスからフォルダー名を取得します。</p>


<p class="wp-block-paragraph">os.listdirメソッド<br>指定されたフォルダー内のファイルとサブフォルダーのリストを取得します。</p>


<p class="wp-block-paragraph">merger.appendメソッド<br>指定されたPDFファイルを結合するために追加します。</p>


<p class="wp-block-paragraph">merger.writeメソッド<br>結合されたPDFファイルを指定されたパスに保存します。</p>


<p class="wp-block-paragraph">merger.closeメソッド<br>PdfMergerオブジェクトを閉じてリソースを解放します。</p>


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_6694" class="wp-block-image "><img decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">フォルダー選択ダイアログが表示されるので、結合したいPDFファイルが含まれているフォルダーを選択します。</p>


<p class="wp-block-paragraph">選択されたフォルダー内のすべてのPDFファイルが結合され、新しいPDFファイルとして保存されます。</p>


<h2 class="wp-block-heading">フォルダー内のPDFを1ページずつ分割</h2>


<p class="wp-block-paragraph">次にユーザーが選択したフォルダー内の<strong>すべてのPDFファイルを各ページごとに分割</strong>し、個別のPDFファイルとして保存します。</p>


<p class="wp-block-paragraph"><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, 'split_pages')
    os.makedirs(output_folder, exist_ok=True)

    # フォルダー内のすべてのPDFファイルを処理
    for filename in os.listdir(folder_path):
        if filename.endswith('.pdf'):
            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'{os.path.splitext(filename)[0]}_page_{page_num + 1}.pdf')
                with open(output_filename, 'wb') 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 class="wp-block-paragraph"><strong>上記と同じモジュールとフィールドは省略します。</strong></p>


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


<p class="wp-block-paragraph">「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 class="wp-block-paragraph">PdfReaderクラス<br>PDFファイルを読み取るためのオブジェクトを提供します。<br><strong>PDFファイルを開いてページごとの情報にアクセス</strong>できます。</p>


<p class="wp-block-paragraph">PdfWriterクラス<br>PDFファイルを作成するためのオブジェクトを提供します。<br><strong>ページを追加して新しいPDFファイルとして保存</strong>します。</p>


<p class="wp-block-paragraph">os.path.joinメソッド<br>複数のパスコンポーネントを結合して<strong>1つのパスを作成</strong>します。</p>


<p class="wp-block-paragraph">os.makedirsメソッド<br>指定されたパスにディレクトリを作成します。<br><strong>exist_ok=Trueオプション</strong>を指定することで、すでに存在する場合でもエラーを発生させません。</p>


<p class="wp-block-paragraph">os.listdirメソッド<br>指定されたフォルダー内のファイルとサブフォルダーのリストを取得します。</p>


<p class="wp-block-paragraph">pdf_writer.add_pageメソッド<br>PdfWriterオブジェクトにページを追加します。</p>


<p class="wp-block-paragraph">pdf_writer.writeメソッド<br>PdfWriterオブジェクトの内容を指定されたファイルに書き込みます。</p>


<p class="wp-block-paragraph">os.path.splitextメソッド<br>ファイル名と拡張子を分割します。</p>


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


<figure class="wp-block-image size-full"><figure id="attachment_mmd_6695" class="wp-block-image "><img decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000.webp" class="attachment-full size-full" alt="" loading="lazy" /></figure></figure>


<p class="wp-block-paragraph">フォルダー選択ダイアログが表示されるので、分割したいPDFファイルが含まれているフォルダーを選択します。</p>


<p class="wp-block-paragraph">選択されたフォルダー内のすべてのPDFファイルがページごとに分割され、新しいPDFファイルとして保存されます。</p>


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


<p class="wp-block-paragraph">この記事では、Pythonを使ってPDFファイルを結合および分割する方法を紹介しました。<br>PyPDF2ライブラリを使用することで、これらの操作を簡単に実行できます。</p>


<p class="wp-block-paragraph">業務効率化や資料管理の向上に有効となります。</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>
