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

<image>
	<url>https://alicia-ing.com/wp-content/uploads/2023/05/cropped-alicia-32x32.webp</url>
	<title>Tkinter | アリッシアの朝</title>
	<link>https://alicia-ing.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】cmakeを使った顔のランドマーク検出システム</title>
		<link>https://alicia-ing.com/programming/python/cmake-face-landmark/</link>
					<comments>https://alicia-ing.com/programming/python/cmake-face-landmark/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Wed, 16 Oct 2024 22:00:00 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=7302</guid>

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



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



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



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



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



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



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



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



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



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



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="7302" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">cmakeとは</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-2">用途</a></li><li class="rtoc-item"><a href="#rtoc-3">インストール方法</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">顔ランドマーク（3Dマスク）の検出</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-5">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-6">解説</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-7">実演</a></li><li class="rtoc-item"><a href="#rtoc-8">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">cmakeとは</h2>



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



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



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



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



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



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



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



<p></p>



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



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



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



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



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



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

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

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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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



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



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



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



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



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



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



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="7044" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">画面（ウィンドウ）作成</a></li><li class="rtoc-item"><a href="#rtoc-2">スライダーバーの作成</a></li><li class="rtoc-item"><a href="#rtoc-3">初期値の設定</a></li><li class="rtoc-item"><a href="#rtoc-4">オプション一覧（色・フォント・大きさ変更・デザインなど）</a></li><li class="rtoc-item"><a href="#rtoc-5">matplotlibグラフをスライダーで操作する</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-6">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-7">解説</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-8">実演</a></li><li class="rtoc-item"><a href="#rtoc-9">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">画面（ウィンドウ）作成</h2>



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



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

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

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

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



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



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



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



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



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

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

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

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



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



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



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



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



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



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



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



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



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



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

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

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

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



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



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



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



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



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

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

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

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



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



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



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



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



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



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



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



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



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



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



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

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



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



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

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

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

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


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


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

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

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

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

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

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

update_graph()  # 初期表示

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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



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



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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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



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



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



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



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="7029" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">画面（ウィンドウ）の作成</a></li><li class="rtoc-item"><a href="#rtoc-2">リストボックスの作成</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">値を取得、選択、削除</a></li><li class="rtoc-item"><a href="#rtoc-4">スクロールバーの追加</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-5">オプション一覧（色・フォント・大きさ変更・デザインなど）</a></li><li class="rtoc-item"><a href="#rtoc-6">エントリーの文字列をリストに追加する</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-7">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-8">解説</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-9">実演</a></li><li class="rtoc-item"><a href="#rtoc-10">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">画面（ウィンドウ）の作成</h2>



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



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



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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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

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



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



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

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

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

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

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

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



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



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



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



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

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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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

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



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



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



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

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



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



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

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



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



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



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

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



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



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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



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



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



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



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



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



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="6989" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">画面（ウィンドウ）作成</a></li><li class="rtoc-item"><a href="#rtoc-2">ラジオボタンの作成</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">ラジオボタンを使用する用途</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-4">オプション一覧（色・フォントなど）</a></li><li class="rtoc-item"><a href="#rtoc-5">ラジオボタンを複数（グループ化）する</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-6">縦、横並びの方法</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-7">初期値を指定して、選択した値に更新</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-8">イベント処理・追加方法</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-9">ラジオボタンの選択でラベルの表示と文字、色を変更</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-10">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-11">解説</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-12">実演</a></li><li class="rtoc-item"><a href="#rtoc-13">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">画面（ウィンドウ）作成</h2>



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



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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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

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

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

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

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

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

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



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



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



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



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



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



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



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



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



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



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



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

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

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

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

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

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

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

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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



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



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



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



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



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



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



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="6949" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">画面（ウィンドウ）作成</a></li><li class="rtoc-item"><a href="#rtoc-2">エントリー(Entry)作成</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">Pack()</a></li><li class="rtoc-item"><a href="#rtoc-4">grid()</a></li><li class="rtoc-item"><a href="#rtoc-5">Place()</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-6">オプション一覧（色・フォントなど）</a></li><li class="rtoc-item"><a href="#rtoc-7">Entryウィジェットから文字列の取得・セット(初期値設定)・クリア</a></li><li class="rtoc-item"><a href="#rtoc-8">入力値をリアルタイムで表示</a></li><li class="rtoc-item"><a href="#rtoc-9">Enter(Return)キーで入力値を取得</a></li><li class="rtoc-item"><a href="#rtoc-10">Pythonでログインフォームを作成する</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-11">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-12">解説</a></li><li class="rtoc-item"><a href="#rtoc-13">実演</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-14">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">画面（ウィンドウ）作成</h2>



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



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



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

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



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="380" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1024x380.webp" alt="" class="wp-image-6957" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1024x380.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-300x111.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-768x285.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack.webp 1055w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



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



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



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



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



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



<p>pack()メソッドは、ウィジェットをウィンドウに配置する際に、<br>シンプルで自動的な位置決定を行う方法です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>entry = tk.Entry(root)
entry.pack(side=tk.TOP, padx=10, pady=10)</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="380" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-1024x380.webp" alt="" class="wp-image-6958" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-1024x380.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-300x111.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1-768x285.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-pack-1.webp 1055w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



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



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



<p>grid()メソッドは、ウィジェットを行と列のグリッドに沿って配置する方法です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>entry = tk.Entry(root)
entry.grid(row=0, column=0, padx=10, pady=10)</code></pre></div>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="350" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-1024x350.webp" alt="" class="wp-image-6959" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-1024x350.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-300x103.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid-768x263.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-grid.webp 1094w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



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



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



<p>place()メソッドは、ウィジェットをピクセル単位で正確に配置するための方法です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>entry = tk.Entry(root)
entry.place(x=50, y=50)</code></pre></div>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1006" height="410" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-place.webp" alt="" class="wp-image-6961" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-place.webp 1006w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-place-300x122.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-place-768x313.webp 768w" sizes="(max-width: 1006px) 100vw, 1006px" /></figure>



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



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



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



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-1024x315.webp" alt="" class="wp-image-6962" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-1024x315.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-300x92.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-option-768x236.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-option.webp 1258w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>entry = tk.Entry(root, bg=&quot;lightblue&quot;, font=(&quot;Arial&quot;, 12), width=30)
entry.pack()</code></pre></div>



<h2 id="rtoc-7"  class="wp-block-heading">Entryウィジェットから文字列の取得・セット(初期値設定)・クリア</h2>



<p>エントリーボックスに入力された文字列を取得するには、get()メソッドを使います。<br>また、insert()メソッドで初期値を設定したり、delete()メソッドで入力をクリアすることも可能です。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="426" src="https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-1024x426.webp" alt="" class="wp-image-6963" srcset="https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-1024x426.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-300x125.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-value-768x320.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/09/entry-value.webp 1148w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code># 文字列の取得
text = entry.get()

# 文字列のセット
entry.insert(0, &quot;アリッシアの朝&quot;)

# クリア
entry.delete(0, tk.END)</code></pre></div>



<p>さらに改良をして、ボタンを押すと、テキストを取得し、エントリーの文字を削除するようにします。</p>



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



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

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



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



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

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



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

def display_text():
    # エントリーから文字を取得
    text = entry.get()
    # ラベルに表示
    label2.config(text=text)
    # エントリーをクリア
    entry.delete(0, tk.END)

root = tk.Tk()
root.title(&quot;Sample&quot;)
root.geometry(&quot;300x200&quot;)  # サイズを指定

# ラベル 
label1 = tk.Label(root, text=&quot;名前を入力してください&quot;)
label1.pack(pady=10)

# エントリーウィジェット
entry = tk.Entry(root)
entry.insert(0, &quot;アリッシアの朝&quot;)
entry.pack(pady=10)

# ボタン
button = tk.Button(root, text=&quot;取得&quot;, command=display_text)
button.pack(pady=10)

# ラベル (取得した文字を表示するため)
label2 = tk.Label(root, text=&quot;&quot;)
label2.pack(pady=10)

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



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



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



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



<p>ユーザーがエントリーボックスに入力した内容を<strong>リアルタイム</strong>で、画面に反映させる方法について解説します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>def show_input(*args):
    print(entry.get())

entry_var = tk.StringVar()
entry_var.trace(&quot;w&quot;, show_input)

entry = tk.Entry(root, textvariable=entry_var)
entry.pack()</code></pre></div>



<p>traceメソッドを使って、入力が変更されるたびに反応する仕組みを作ることができます。</p>



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



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



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



<p>ユーザーが入力を終えた後、Enterキーを押したタイミングでエントリーボックスから入力値を取得する方法を紹介します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>def on_enter(event):
    print(&quot;入力値:&quot;, entry.get())

entry.bind(&quot;&lt;Return&gt;&quot;, on_enter)</code></pre></div>



<p>bindを使うことでイベントを追加できます。</p>



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



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

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



<p>これにより、フォーム送信や次の処理に進む操作を自然な形で実現できます。</p>



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



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



<p>Pythonでログインフォームを作るには、TkinterのEntryが有効です。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-blue-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#0095d9"><div class="tab-caption-box-label block-box-label box-label fab-bolt"><span class="tab-caption-box-label-text block-box-label-text box-label-text">Pythonでログインフォームをつくる</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>ログイン画面の作成：エントリーウィジェットでユーザー名とパスワードを入力します。</li>



<li>入力値の検証：get()メソッドを使ってエントリーから値を取得し、<br>正しいかどうかを確認します。</li>



<li>画面遷移：正しいユーザー名とパスワードが入力されると、<br>新しいウィンドウ（画面B）が開き、エントリーボックスで新しいパスワードを設定できます。</li>



<li>パスワードの変更：新しいパスワードが正しい形式かどうかを正規表現でチェックし、<br>問題がなければ変更が完了します。</li>
</ul>
</div></div>



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



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

<a target="_self" href="https://alicia-ing.com/programming/python/change_screen/" title="【Python】Tkinter画面遷移-複数ウィンドウをクラス化" class="blogcard-wrap internal-blogcard-wrap a-wrap cf"><div class="blogcard internal-blogcard ib-left cf"><div class="blogcard-label internal-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail internal-blogcard-thumbnail"><img loading="lazy" decoding="async" width="160" height="90" src="https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-160x90.webp" class="blogcard-thumb-image internal-blogcard-thumb-image wp-post-image" alt="" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/05/change_screen-320x180.webp 320w" sizes="(max-width: 160px) 100vw, 160px" /></figure><div class="blogcard-content internal-blogcard-content"><div class="blogcard-title internal-blogcard-title">【Python】Tkinter画面遷移-複数ウィンドウをクラス化</div><div class="blogcard-snippet internal-blogcard-snippet">Tkinterの複数ウィンドウを画面遷移するには、pack_forget()メソッドを使います。ボタンでクリックすると表示と非表示をして画面切り替えをします。複雑な画面遷移は、def関数では読みにくいのでクラス化して可読性を上げます。</div></div><div class="blogcard-footer internal-blogcard-footer cf"><div class="blogcard-site internal-blogcard-site"><div class="blogcard-favicon internal-blogcard-favicon"><img loading="lazy" decoding="async" src="https://www.google.com/s2/favicons?domain=https://alicia-ing.com" alt="" class="blogcard-favicon-image internal-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain internal-blogcard-domain">alicia-ing.com</div></div><div class="blogcard-date internal-blogcard-date"><div class="blogcard-post-date internal-blogcard-post-date">2025.03.10</div></div></div></div></a>
</div>



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



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

# 初期の正しいユーザー名とパスワード
initial_username = &quot;アリッシア&quot;
initial_password = &quot;Alicia-ing&quot;

# グローバル変数を使ってパスワードを更新可能にする
current_password = initial_password

# パスワードのバリデーション関数
def validate_password(password):
    # 大文字、小文字、記号を含むかチェック
    if (re.search(r&#39;[A-Z]&#39;, password) and  # 大文字
        re.search(r&#39;[a-z]&#39;, password) and  # 小文字
        re.search(r&#39;[\W_]&#39;, password)):    # 記号
        return True
    else:
        return False

# 画面Aのログイン処理
def login():
    global current_password
    username = entry_username.get()
    password = entry_password.get()

    if username == &quot;&quot; or password == &quot;&quot;:
        message_label.config(text=&quot;入力を完了してください&quot;, fg=&quot;red&quot;)
    elif username != initial_username or password != current_password:
        message_label.config(text=&quot;パスワードが異なります&quot;, fg=&quot;red&quot;)
        entry_username.delete(0, tk.END)  # 入力フィールドをクリア
        entry_password.delete(0, tk.END)  # 入力フィールドをクリア
    else:
        # 画面Bへ遷移
        open_screen_b(username)

# 画面Bを開く関数
def open_screen_b(username):
    screen_a.withdraw()  # 画面Aを非表示にする
    screen_b = tk.Toplevel()  # 新しいウィンドウ（画面B）
    screen_b.title(&quot;画面B&quot;)
    screen_b.geometry(&quot;300x200&quot;)  # 画面サイズの指定

    label_greeting = tk.Label(screen_b, text=f&quot;Hello, {username}&quot;, font=(&quot;Arial&quot;, 14))
    label_greeting.pack(pady=10)

    label_new_password = tk.Label(screen_b, text=&quot;新しいパスワード:&quot;)
    label_new_password.pack(pady=5)

    new_password_entry = tk.Entry(screen_b)
    new_password_entry.pack(pady=5)

    # エンターキーが押されたらパスワード変更を実行
    new_password_entry.bind(&quot;&lt;Return&gt;&quot;, lambda event: change_password())

    def change_password():
        new_password = new_password_entry.get()
        if validate_password(new_password):
            global current_password
            current_password = new_password  # パスワードを更新
            messagebox.showinfo(&quot;成功&quot;, &quot;パスワードが変更されました&quot;)
            screen_b.destroy()  # 画面Bを閉じる
            screen_a.deiconify()  # 画面Aを再表示する
        else:
            messagebox.showerror(&quot;エラー&quot;, &quot;もう一度作成してください (大文字, 小文字, 記号を含む必要があります)&quot;)

    change_button = tk.Button(screen_b, text=&quot;変更&quot;, command=change_password)
    change_button.pack(pady=20)

# メインウィンドウ（画面A）
screen_a = tk.Tk()
screen_a.title(&quot;ログイン画面&quot;)
screen_a.geometry(&quot;300x250&quot;)  # 画面サイズの指定

# ユーザー名入力フィールド
label_username = tk.Label(screen_a, text=&quot;ユーザー名:&quot;)
label_username.pack(pady=5)

entry_username = tk.Entry(screen_a)
entry_username.pack(pady=5)

# パスワード入力フィールド
label_password = tk.Label(screen_a, text=&quot;パスワード:&quot;)
label_password.pack(pady=5)

entry_password = tk.Entry(screen_a, show=&quot;*&quot;)  # パスワード非表示
entry_password.pack(pady=5)

# メッセージラベル（エラーメッセージ表示用）
message_label = tk.Label(screen_a, text=&quot;&quot;)
message_label.pack(pady=5)

# ログインボタン
login_button = tk.Button(screen_a, text=&quot;ログイン&quot;, command=login)
login_button.pack(pady=20)

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



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



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



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



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



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



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



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



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



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



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



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



<p>「tkinter」：Pythonの標準ライブラリで、GUIアプリケーションを作成するために使用。「tkinter.messagebox」：GUIアプリケーション内で情報やエラーメッセージを表示するダイアログボックスを提供する。<br>「re」：正規表現を利用した文字列のパターンマッチングを行うために使用。パスワードのバリデーションに活用されている。</p>



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



<p>「initial_username」：初期の正しいユーザー名を保持する変数。ログイン時にユーザー入力と比較するために使用。<br>「initial_password」：初期の正しいパスワードを保持する変数。ログイン時にパスワード入力と比較するために使用。<br>「current_password」：現在のパスワードを保持するグローバル変数。パスワード変更後に更新され、ログイン時に使用される。<br>「screen_a」：ログイン画面（画面A）のウィンドウオブジェクトを保持。GUIのメインウィンドウを表す。<br>「screen_b」：パスワード変更画面（画面B）のウィンドウオブジェクト。ログイン成功後に新たに作成される。<br>「entry_username」：ユーザー名を入力するテキストフィールド。ユーザーがログイン時に使用する。<br>「entry_password」：パスワードを入力するテキストフィールド。ユーザーがログイン時に使用する。<br>「message_label」：ログイン時のエラーメッセージや案内メッセージを表示するためのラベル。</p>



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



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



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



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



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



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



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



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



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



<p>Tkinterを使ってエントリーボックスを作成し、文字列の取得やセット、クリア、そしてリアルタイムでの表示といった操作を行う方法について学びました。<br>エントリーウィジェットは、ユーザーとのインタラクションを強化するために欠かせない要素です。</p>



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



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/tkinter-entry/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】PDF結合・分割｜PyPDF2の使い方</title>
		<link>https://alicia-ing.com/programming/python/pypdf-edit/</link>
					<comments>https://alicia-ing.com/programming/python/pypdf-edit/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Thu, 11 Jul 2024 12:00:12 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=6684</guid>

					<description><![CDATA[Pythonを使えば、複数のPDFファイルを1つに結合とPDFファイルを１つずつ分割することが簡単にできます。 本記事では、PyPDF2ライブラリを使用してPDFを分割や結合などの操作を実行する方法を詳しく解説します。  [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>PDFファイルを結合する。</li>
</ul>



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



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



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



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



<p>本記事では、PyPDF2ライブラリを使用してPDFを分割や結合などの操作を実行する方法を詳しく解説します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>PythonでPDFを操作したい。</li>



<li>紙の書類をデジタル化し、管理したい</li>



<li>多数のPDFファイルを扱いたい人</li>



<li>学術論文や研究資料を整理する学生や研究者</li>



<li>PDFを利用したドキュメント管理を効率化したいエンジニア</li>
</ul>
</div></div>



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="6684" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">PyPDF2の機能と使う場面</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-2">PDFの結合</a></li><li class="rtoc-item"><a href="#rtoc-3">PDFファイルをページ単位で分割</a></li><li class="rtoc-item"><a href="#rtoc-4">ページの抽出</a></li><li class="rtoc-item"><a href="#rtoc-5">PDFのメタデータを読み取る</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-6">フォルダー内すべてのPDFを1つに結合</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-7">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-8">解説</a></li><li class="rtoc-item"><a href="#rtoc-9">実演</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-10">フォルダー内のPDFを1ページずつ分割</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-11">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-12">解説</a></li><li class="rtoc-item"><a href="#rtoc-13">実演</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-14">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">PyPDF2の機能と使う場面</h2>



<p>PyPDF2は、PythonでPDFファイルを操作するためのライブラリです。</p>



<div class="wp-block-cocoon-blocks-tab-caption-box-1 tab-caption-box block-box has-border-color has-light-green-border-color not-nested-style cocoon-block-tab-caption-box" style="--cocoon-custom-border-color:#8bc34a"><div class="tab-caption-box-label block-box-label box-label fab-thumbs-up"><span class="tab-caption-box-label-text block-box-label-text box-label-text">PyPDF2を使う場面</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li><strong>PDFの結合と分割</strong>: 複数のPDFファイルを一つにまとめる、PDFファイルをページ単位で分割。</li>



<li><strong>ページの抽出と追加</strong>: 特定のページを抽出、新しいページの追加。</li>



<li><strong>メタデータの操作</strong>: PDFのメタデータ（タイトル、著者、作成日など）の読み取り、変更。</li>
</ul>
</div></div>



<h3 id="rtoc-2"  class="wp-block-heading">PDFの結合</h3>



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

# PDFファイルを読み込む
pdf1 = open(&#39;document1.pdf&#39;, &#39;rb&#39;)
pdf2 = open(&#39;document2.pdf&#39;, &#39;rb&#39;)

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

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

# 結合されたPDFをファイルとして書き出し
with open(&#39;new_document.pdf&#39;, &#39;wb&#39;) as output:
    merger.write(output)

# リソースを解放
pdf1.close()
pdf2.close()
merger.close()</code></pre></div>



<h3 id="rtoc-3"  class="wp-block-heading">PDFファイルをページ単位で分割</h3>



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

# 分割するPDFファイルを開く
input_pdf = open(&#39;document.pdf&#39;, &#39;rb&#39;)

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

# 分割されたページを新しいPDFファイルとして保存
for i in range(len(reader.pages)):
    writer = PyPDF2.PdfWriter()
    writer.add_page(reader.pages[i])
    
    with open(f&#39;page_{i+1}.pdf&#39;, &#39;wb&#39;) as output_pdf:
        writer.write(output_pdf)

# リソースを解放
input_pdf.close()</code></pre></div>



<h3 id="rtoc-4"  class="wp-block-heading">ページの抽出</h3>



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

# 抽出するPDFファイルを開く
input_pdf = open(&#39;document.pdf&#39;, &#39;rb&#39;)

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

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

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

# 抽出したページを保存
with open(&#39;extracted_page.pdf&#39;, &#39;wb&#39;) as output_pdf:
    writer.write(output_pdf)

# リソースを解放
input_pdf.close()</code></pre></div>



<h3 id="rtoc-5"  class="wp-block-heading">PDFのメタデータを読み取る</h3>



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

# PDFファイルを開く
input_pdf = open(&#39;document.pdf&#39;, &#39;rb&#39;)

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

# メタデータを取得
metadata = reader.metadata

# メタデータを表示
print(metadata)

# リソースを解放
input_pdf.close()
</code></pre></div>



<h2 id="rtoc-6"  class="wp-block-heading">フォルダー内すべてのPDFを1つに結合</h2>



<p>ユーザーが選択したフォルダー内の<strong>すべてのPDFファイルを結合</strong>し、1つのPDFファイルとして保存します。</p>



<p>Tkinterを使用してフォルダー選択ダイアログを表示し、選択されたフォルダー内のPDFファイルを<strong>PyPDF2のPdfMergerクラス</strong>で結合します。</p>



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



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import os
from PyPDF2 import PdfMerger
from tkinter import Tk, filedialog

# Tkinterを使用してフォルダー選択ダイアログを表示
root = Tk()
root.withdraw()  # メインウィンドウを表示しないようにする
folder_path = filedialog.askdirectory()

if folder_path:
    # フォルダー名を取得
    folder_name = os.path.basename(folder_path)

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

    # フォルダー内のすべてのPDFファイルを取得し、結合
    for filename in os.listdir(folder_path):
        if filename.endswith(&#39;.pdf&#39;):
            file_path = os.path.join(folder_path, filename)
            merger.append(file_path)

    # 結合されたPDFファイルの保存
    output_path = os.path.join(folder_path, f&#39;{folder_name}.pdf&#39;)
    merger.write(output_path)
    merger.close()

    print(f&quot;結合されたPDFファイルが{output_path}に保存されました。&quot;)
else:
    print(&quot;フォルダーが選択されませんでした。&quot;)
</code></pre></div>



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



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



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



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



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



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



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



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



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



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



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



<p>「os」：ファイルパスの操作やフォルダーのリストを取得します。<br>「PyPDF2」：PDFファイルの読み取りおよび書き込みを行います。<br>「tkinter」：GUIを使用してフォルダー選択ダイアログを表示します。</p>



<p><strong>PyPDFは、標準ライブラリではない</strong>ので、インストール必要があります。<br>コマンドプロンプト（Windows）に入力して、実行します。</p>



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



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



<p>「root」：Tkinterのメインウィンドウオブジェクト。GUIダイアログの親ウィンドウとして機能する。<br>「folder_path」：ユーザーが選択したフォルダーのパス。<br>「folder_name」：選択したフォルダーの名前。<br>「merger」：PDFファイルを結合するためのPdfMergerオブジェクト。<br>「output_path」：結合されたPDFファイルの保存先パス。</p>



<ul class="wp-block-list">
<li><strong>それぞれのクラス（関数・メソッド）</strong></li>
</ul>



<p>PdfMergerクラス<br>PDFファイルを結合するためのオブジェクトを提供します。<br>ファイルを追加していき、<strong>最終的に1つのPDFファイルとして出力</strong>します。</p>



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



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



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



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



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



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



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



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



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000.webp" alt="" class="wp-image-6694" srcset="https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000.webp 1920w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-300x148.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-1024x504.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-768x378.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/07/complete2_0000-1536x756.webp 1536w" sizes="(max-width: 1920px) 100vw, 1920px" /></figure>



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



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



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



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



<p><strong>フォルダー内の各PDFファイルを読み込み</strong>、それぞれのページを新しいPDFファイルとして保存します。</p>



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



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import os
from PyPDF2 import PdfReader, PdfWriter
from tkinter import Tk, filedialog

# Tkinterを使用してフォルダー選択ダイアログを表示
root = Tk()
root.withdraw()  # メインウィンドウを表示しないようにする
folder_path = filedialog.askdirectory()

if folder_path:
    # 出力用のフォルダーを作成
    output_folder = os.path.join(folder_path, &#39;split_pages&#39;)
    os.makedirs(output_folder, exist_ok=True)

    # フォルダー内のすべてのPDFファイルを処理
    for filename in os.listdir(folder_path):
        if filename.endswith(&#39;.pdf&#39;):
            file_path = os.path.join(folder_path, filename)
            pdf = PdfReader(file_path)

            # 各ページを個別のPDFファイルとして保存
            for page_num in range(len(pdf.pages)):
                pdf_writer = PdfWriter()
                pdf_writer.add_page(pdf.pages[page_num])

                # 新しいPDFファイル名を作成
                output_filename = os.path.join(output_folder, f&#39;{os.path.splitext(filename)[0]}_page_{page_num + 1}.pdf&#39;)
                with open(output_filename, &#39;wb&#39;) as output_pdf:
                    pdf_writer.write(output_pdf)

    print(f&quot;分割されたPDFファイルが{output_folder}に保存されました。&quot;)
else:
    print(&quot;フォルダーが選択されませんでした。&quot;)
</code></pre></div>



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



<p><strong>上記と同じモジュールとフィールドは省略します。</strong></p>



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



<p>「filename」：現在処理中のPDFファイルの名前。<br>「file_path」：現在処理中のPDFファイルのフルパス。<br>「pdf」：現在読み込まれているPDFファイルのPdfReaderオブジェクト。<br>「page_num」：現在処理中のページ番号。<br>「pdf_writer」：新しいPDFファイルを作成するためのPdfWriterオブジェクト。<br>「output_filename」：分割された各ページのPDFファイル名。</p>



<ul class="wp-block-list">
<li><strong>それぞれのクラス（関数・メソッド）</strong></li>
</ul>



<p>PdfReaderクラス<br>PDFファイルを読み取るためのオブジェクトを提供します。<br><strong>PDFファイルを開いてページごとの情報にアクセス</strong>できます。</p>



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



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



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



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



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



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



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



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



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000.webp" alt="" class="wp-image-6695" srcset="https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000.webp 1920w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-300x148.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-1024x504.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-768x378.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/07/complete1_0000-1536x756.webp 1536w" sizes="(max-width: 1920px) 100vw, 1920px" /></figure>



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



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



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



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



<p>業務効率化や資料管理の向上に有効となります。</p>



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



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/pypdf-edit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】zipファイルの操作｜解凍・展開や圧縮する方法</title>
		<link>https://alicia-ing.com/programming/python/zip-operation/</link>
					<comments>https://alicia-ing.com/programming/python/zip-operation/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Wed, 10 Jul 2024 14:23:28 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=6682</guid>

					<description><![CDATA[Pythonは、zipファイルを操作、解凍（展開）・圧縮することができます。Pythonを使って効率的にファイルを管理し、ディスクスペースを節約するテクニックを身につけることができます。 本記事では、zipファイルの解凍 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<p>フォルダー内のファイルをzipファイルにする。</p>



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



<p>Pythonは、zipファイルを操作、解凍（展開）・圧縮することができます。<br>Pythonを使って効率的にファイルを管理し、ディスクスペースを節約するテクニックを身につけることができます。</p>



<p>本記事では、zipファイルの解凍・展開から圧縮まで、基本的な操作方法を詳しく解説します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>大量のファイルを効率的に管理したい</li>



<li>バックアップやデータ転送のためにファイルを圧縮したい</li>



<li>Pythonでのファイル操作を学びたい</li>



<li>ディスクスペースを有効に使いたい</li>



<li>プロジェクトのファイル整理を自動化したい</li>
</ul>
</div></div>



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="6682" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">zipファイルはいつ使う？</a></li><li class="rtoc-item"><a href="#rtoc-2">zipfile（ライブラリ）</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">ZIPファイルの作成</a></li><li class="rtoc-item"><a href="#rtoc-4">ZIPファイルの解凍</a></li><li class="rtoc-item"><a href="#rtoc-5">ZIPファイルの追加</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-6">フォルダーを選択して全てのzipファイルを展開・解凍する</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-7">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-8">解説</a></li><li class="rtoc-item"><a href="#rtoc-9">実演</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-10">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">zipファイルはいつ使う？</h2>



<p>zipファイルは、複数のファイルやフォルダーを1つの圧縮ファイルにまとめることができます。<br>したがって、データの管理がしやすく、利便性が高いです。</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">zipファイルの用途</span></div><div class="tab-caption-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>ファイルのバックアップ</li>



<li>大量のファイルをメールで送信</li>



<li>データのアーカイブ</li>



<li>ウェブからのファイルダウンロード</li>



<li>プロジェクトファイルの整理と管理</li>
</ul>
</div></div>



<p>これら用途には、ディスクスペースの節約やファイル転送の高速化、データの整合性維持する必要があるので、zipファイル形式は重宝されます。</p>



<h2 id="rtoc-2"  class="wp-block-heading">zipfile（ライブラリ）</h2>



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



<p>zipfileライブラリは、Pythonの標準ライブラリです。</p>



<p>したがって、pipでインストール必要はありません。</p>



<h3 id="rtoc-3"  class="wp-block-heading">ZIPファイルの作成</h3>



<p>ファイルやフォルダーを圧縮してZIPファイルを作成します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import zipfile
import os

def create_zip(zip_name, file_paths):
    with zipfile.ZipFile(zip_name, &#39;w&#39;) as zipf:
        for file in file_paths:
            zipf.write(file, os.path.basename(file))

create_zip(&#39;example.zip&#39;, [&#39;file1.txt&#39;, &#39;file2.txt&#39;, &#39;folder/file3.txt&#39;])</code></pre></div>



<p>実行すると、<strong>file1、file2、folder内のfile3のテキストがexample.zipで作成</strong>されます。</p>



<h3 id="rtoc-4"  class="wp-block-heading">ZIPファイルの解凍</h3>



<p>ZIPファイル内のすべてのファイルや特定のファイルを解凍します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import zipfile
import os

def extract_all(zip_name, extract_to=&#39;.&#39;):
    with zipfile.ZipFile(zip_name, &#39;r&#39;) as zipf:
        zipf.extractall(extract_to)

# 使用例
extract_all(&#39;example.zip&#39;, &#39;extracted_all&#39;)</code></pre></div>



<p>実行すると、<strong>example.zip内のファイルをすべてextracted_allフォルダーに解凍</strong>します。</p>



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



<h3 id="rtoc-5"  class="wp-block-heading">ZIPファイルの追加</h3>



<p>既存のZIPファイルに新しいファイルを追加します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import zipfile
import os

def add_to_zip(zip_name, file_paths):
    with zipfile.ZipFile(zip_name, &#39;a&#39;) as zipf:
        for file in file_paths:
            zipf.write(file, os.path.basename(file))

add_to_zip(&#39;example.zip&#39;, [&#39;new_file.txt&#39;])
</code></pre></div>



<p>実行すると、<strong>example.zipにnew_file.txtを追加</strong>します。</p>



<h2 id="rtoc-6"  class="wp-block-heading">フォルダーを選択して全てのzipファイルを展開・解凍する</h2>



<p>上記のスクリプトは、example.zipのみを操作していましたが、このコードは、指定したフォルダー内のすべてのZIPファイルを再帰的に検索し、解凍します。</p>



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



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

def extract_zip(zip_path, extract_to):
    with zipfile.ZipFile(zip_path, &#39;r&#39;) as zip_ref:
        folder_name = os.path.splitext(os.path.basename(zip_path))[0]
        extract_folder = os.path.join(extract_to, folder_name)
        os.makedirs(extract_folder, exist_ok=True)
        zip_ref.extractall(extract_folder)

def extract_all_zips_in_folder(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(&#39;.zip&#39;):
                file_path = os.path.join(root, file)
                print(f&quot;Extracting {file_path}&quot;)
                extract_zip(file_path, root)

def select_folder():
    root = tk.Tk()
    root.withdraw()
    folder_path = filedialog.askdirectory()
    return folder_path

if __name__ == &quot;__main__&quot;:
    folder_path = select_folder()
    if folder_path:
        extract_all_zips_in_folder(folder_path)
    else:
        print(&quot;フォルダーが選択されていません。&quot;)
</code></pre></div>



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



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



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



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



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



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



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



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



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



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



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



<p>「os」：ファイルやディレクトリの操作に必要。<br>「zipfile」：<strong>ZIPファイルの圧縮・解凍に必要。</strong><br>「tkinter」：GUIを作成するためのライブラリ。<br>「filedialog」：<strong>GUIを通じてフォルダやファイルを選択するために必要</strong>。</p>



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



<p>「folder_name」：ZIPファイル名から拡張子を除いた名前を持つフォルダの名前。<br>解凍先のフォルダ名として使用される。<br>「extract_folder」：解凍したファイルを保存するフォルダのパス。<br>「folder_path」：ユーザーが選択したフォルダのパス。解凍処理の対象となるフォルダ。<br>「file_path」：解凍するZIPファイルのフルパス。</p>



<ul class="wp-block-list">
<li><strong>それぞれのクラス（関数・メソッド）</strong></li>
</ul>



<p>extract_zip関数<br>ZIPファイルを解凍するための関数。<br>引数として「zip_path」（ZIPファイルのパス）と「extract_to」（解凍先のディレクトリ）を取ります。<br>指定されたZIPファイルを「extract_to」ディレクトリ内の<strong>ZIPファイル名と同じ名前のフォルダに解凍</strong>します。</p>



<p>extract_all_zips_in_folder関数<br>指定されたフォルダ内の<strong>すべてのZIPファイルを再帰的に探索し、見つけたZIPファイルを解凍する</strong>関数。引数として「folder_path」（対象フォルダのパス）を取ります。<br>フォルダ内のZIPファイルを見つけ次第、extract_zip関数を呼び出して解凍する。</p>



<p>select_folder関数<br>ユーザーがフォルダを選択するためのGUIを表示する関数。<br><strong>ファイルダイアログを使用してフォルダを選択</strong>し、そのパスを返します。<br>選択されたフォルダのパスを返すため、他の関数で使用される。</p>



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



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1920" height="945" src="https://alicia-ing.com/wp-content/uploads/2024/07/complete_0000.webp" alt="" class="wp-image-6708" srcset="https://alicia-ing.com/wp-content/uploads/2024/07/complete_0000.webp 1920w, https://alicia-ing.com/wp-content/uploads/2024/07/complete_0000-300x148.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/07/complete_0000-1024x504.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/07/complete_0000-768x378.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/07/complete_0000-1536x756.webp 1536w" sizes="(max-width: 1920px) 100vw, 1920px" /></figure>



<p>このスクリプトを実行すると、<strong>フォルダー選択ダイアログが表示</strong>されます。</p>



<p>解凍したいZIPファイルが含まれているフォルダーを選択すると、<strong>フォルダー内のすべてのZIPファイルが解凍</strong>されます。</p>



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



<p>Pythonを使ってzipファイルを操作する方法について学びました。<br>zipfileライブラリを使用すると、ファイルの圧縮や解凍が簡単に行えます。</p>



<p>ファイルのバックアップや転送、アーカイブ管理など、<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/zip-operation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】フォルダー内の画像をpdfに変換・編集する</title>
		<link>https://alicia-ing.com/programming/python/images-to-pdf/</link>
					<comments>https://alicia-ing.com/programming/python/images-to-pdf/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Mon, 08 Jul 2024 07:34:26 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=6624</guid>

					<description><![CDATA[画像ファイルを一つのPDFにまとめることは、プロジェクトやレポート、プレゼンテーションなどで非常に便利です。特に複数の画像ファイルを整理し、一つのファイルとして共有したい場合に役立ちます。 また、大学の講義でスマホで撮影 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box not-nested-style cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-flag"><span class="label-box-label-text block-box-label-text box-label-text">本記事を読むと以下の実行ができます</span></div><div class="label-box-content block-box-content box-content">
<p>フォルダー内の画像をPDFに変換する。</p>



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



<p>画像ファイルを一つのPDFにまとめることは、プロジェクトやレポート、プレゼンテーションなどで非常に便利です。特に複数の画像ファイルを整理し、一つのファイルとして共有したい場合に役立ちます。</p>



<p>また、大学の講義でスマホで撮影した画像をPDFで提出するように求めてくることもあります。</p>



<p>本記事では、Pythonを使ってフォルダー内の画像ファイルを簡単にPDFに変換する方法を紹介します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>複数の画像ファイルを一つにまとめたい</li>



<li>画像をPDFに変換する方法を探している</li>



<li>プロジェクトやレポートに画像を一括で取り込みたい</li>
</ul>
</div></div>



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="6624" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">画像をPDF化するメリット</a></li><li class="rtoc-item"><a href="#rtoc-2">PDF変換するモジュール｜img2pdfの使い方</a></li><li class="rtoc-item"><a href="#rtoc-3">フォルダー内の画像をPDFに変換</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-4">ソースコード</a></li><li class="rtoc-item"><a href="#rtoc-5">解説</a></li><li class="rtoc-item"><a href="#rtoc-6">実演</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-7">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">画像をPDF化するメリット</h2>



<p>画像をPDF化することで、<strong>複数の画像ファイルを一つにまとめる</strong>ことができます。<br>これにより、ファイル管理が容易になり、共有や印刷が簡単になります。</p>



<p>また、PDFは<strong>広くサポートされているフォーマット</strong>であり、PCやiPad、スマートフォンなど異なるデバイスやプラットフォームでも一貫した表示が可能です。</p>



<p>さらに、PDFファイルは<strong>セキュリティ機能</strong>も備えており、パスワード保護や編集制限を設定することができます。</p>



<h2 id="rtoc-2"  class="wp-block-heading">PDF変換するモジュール｜img2pdfの使い方</h2>



<p>画像をPDFに編集するモジュールは、「<a target="_self" href="https://pypi.org/project/img2pdf/">img2pdf</a>」、「FPDF」などがあります。</p>



<div class="wp-block-group alignwide is-layout-constrained wp-block-group-is-layout-constrained">
<div class="wp-block-group alignwide is-layout-constrained wp-block-group-is-layout-constrained">
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-28f84493 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:100%">
<figure class="wp-block-table aligncenter is-style-regular"><div class="scrollable-table"><table><thead><tr><th class="has-text-align-center" data-align="center">項目</th><th class="has-text-align-center" data-align="center">img2pdf</th><th class="has-text-align-center" data-align="center">FPDF</th></tr></thead><tbody><tr><td class="has-text-align-center" data-align="center">使いやすさ</td><td class="has-text-align-center" data-align="center">非常に簡単</td><td class="has-text-align-center" data-align="center">少し難しい</td></tr><tr><td class="has-text-align-center" data-align="center">変換速度</td><td class="has-text-align-center" data-align="center">高速</td><td class="has-text-align-center" data-align="center">img2pdfよりやや遅い</td></tr><tr><td class="has-text-align-center" data-align="center">画像品質</td><td class="has-text-align-center" data-align="center">元の品質を保持</td><td class="has-text-align-center" data-align="center">圧縮で品質が低下する可能性がある</td></tr><tr><td class="has-text-align-center" data-align="center">ファイルサイズ</td><td class="has-text-align-center" data-align="center">大きくなる可能性がある</td><td class="has-text-align-center" data-align="center">圧縮で小さくなる</td></tr><tr><td class="has-text-align-center" data-align="center">多機能性</td><td class="has-text-align-center" data-align="center">低機能<br>（画像の変換に特化、テキストNG）</td><td class="has-text-align-center" data-align="center">高機能<br>（テキスト、グラフィック、リンクなどの追加が可能）</td></tr><tr><td class="has-text-align-center" data-align="center">カスタマイズ性</td><td class="has-text-align-center" data-align="center">制限が多い</td><td class="has-text-align-center" data-align="center">高い</td></tr></tbody></table></div></figure>
</div>
</div>
</div>
</div>



<p><strong>img2pdfは、手短なコードで処理できますが、ファイルが大きく</strong>なります。<br>対して、FPDFは、複雑な処理が可能なので、ファイルのサイズを小さくできます。</p>



<div class="wp-block-cocoon-blocks-balloon-ex-box-1 speech-wrap sb-id-1 sbs-stn sbp-l sbis-cb cf block-box not-nested-style cocoon-block-balloon"><div class="speech-person"><figure class="speech-icon"><img decoding="async" src="https://alicia-ing.com/wp-content/uploads/2023/05/alicia.webp" alt="著者の体験談" class="speech-icon-image"/></figure><div class="speech-name">著者の体験談</div></div><div class="speech-balloon">
<p><strong>FPDFは、コードエラーが良く起きた</strong>ので、<br>画像変換だけの場合は、img2pdfを使うのがおすすめ。</p>
</div></div>



<p>img2pdfの場合は、次のようなコードで画像をPDFに変換することができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import img2pdf
from pathlib import Path

# 画像ファイルのパスを指定
image_path = &#39;input.jpg&#39;
images_path =[&#39;input1.jpg&#39;,&#39;input2.jpg&#39;,&#39;input3.jpg&#39;] #複数の画像を１つのPDFにする。
pdf_path = &#39;output.pdf&#39;

# 画像をPDFに変換して保存
with open(pdf_path, &quot;wb&quot;) as f:
    f.write(img2pdf.convert(image_path))

print(f&quot;PDF saved as {pdf_path}&quot;)</code></pre></div>



<h2 id="rtoc-3"  class="wp-block-heading">フォルダー内の画像をPDFに変換</h2>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1987" height="1020" src="https://alicia-ing.com/wp-content/uploads/2024/07/making-pdf.webp" alt="" class="wp-image-6679" srcset="https://alicia-ing.com/wp-content/uploads/2024/07/making-pdf.webp 1987w, https://alicia-ing.com/wp-content/uploads/2024/07/making-pdf-300x154.webp 300w, https://alicia-ing.com/wp-content/uploads/2024/07/making-pdf-1024x526.webp 1024w, https://alicia-ing.com/wp-content/uploads/2024/07/making-pdf-768x394.webp 768w, https://alicia-ing.com/wp-content/uploads/2024/07/making-pdf-1536x788.webp 1536w" sizes="(max-width: 1987px) 100vw, 1987px" /></figure>



<p>フォルダー内の複数の画像ファイルを一つのPDFファイルに変換する手順について説明します。<br>本記事では、Pythonを使用して簡単に実現する方法を紹介します。</p>



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



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import os
from PIL import Image
import img2pdf
import tkinter as tk
from tkinter import filedialog

def select_folder():
    root = tk.Tk()
    root.withdraw()
    folder_path = filedialog.askdirectory()
    return folder_path

def convert_images_to_pdf(folder_path):
    if not folder_path:
        print(&quot;フォルダーが選択されていません。&quot;)
        return
    
    images = []
    for file_name in os.listdir(folder_path):
        if file_name.lower().endswith((&#39;.png&#39;, &#39;.jpg&#39;, &#39;.jpeg&#39;, &#39;.tiff&#39;, &#39;.bmp&#39;, &#39;.gif&#39;)):
            file_path = os.path.join(folder_path, file_name)
            images.append(file_path)
    
    if not images:
        print(&quot;フォルダー内に画像ファイルが見つかりませんでした。&quot;)
        return

    folder_name = os.path.basename(folder_path)
    pdf_path = os.path.join(folder_path, f&quot;{folder_name}.pdf&quot;)
    with open(pdf_path, &quot;wb&quot;) as f:
        f.write(img2pdf.convert(images))
    
    print(f&quot;PDFが作成されました: {pdf_path}&quot;)

if __name__ == &quot;__main__&quot;:
    folder_path = select_folder()
    convert_images_to_pdf(folder_path)</code></pre></div>



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



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



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



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



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



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



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



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



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



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



<p>ユーザーが選択したフォルダー内の画像ファイルをPDFファイルに変換します。</p>



<ul class="wp-block-list">
<li><strong>ライブラリ</strong></li>
</ul>



<p>「os」：ファイルやディレクトリの操作を行うために使用します。<br>「PIL」：Python Imaging Libraryで、画像の操作や変換を行います。<br>「img2pdf」：画像ファイルをPDFに変換します。<br>「tkinter」：GUIを作成し、フォルダー選択ダイアログを表示します。</p>



<ul class="wp-block-list">
<li><strong>変換する画像フォルダーを選択する</strong></li>
</ul>



<p>select_folder関数は、ユーザーにフォルダーを選択させ、そのパスを返します。<br>tk.Tk()でGUIのルートウィンドウを作成し、root.withdraw()で非表示にした後、filedialog.askdirectory()を使用して<strong>フォルダー選択ダイアログを表示</strong>します。</p>



<ul class="wp-block-list">
<li><strong>画像ファイルの収集とPDFの作成</strong></li>
</ul>



<p>convert_images_to_pdf関数は、選択されたフォルダー内の画像ファイルを収集し、PDFに変換します。</p>



<p>フォルダーが選択されていない場合やフォルダー内に画像ファイルがない場合は、<br>エラーメッセージを表示します。</p>



<p>次に、画像ファイルのパスをリストに追加します。<br>各ファイル名が画像の拡張子（.png, .jpg, .jpeg, .tiff, .bmp, .gif）のいずれかで終わる場合、<br>そのファイルのパスを取得します。</p>



<p>最後に、img2pdf.convertを使用してPDFを作成し、指定されたパスに保存します。</p>



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



<p>スクリプトを実行すると、フォルダー選択ダイアログが表示されます。<br>変換したい画像が含まれるフォルダーを選択します。</p>



<p>スクリプトは選択されたフォルダー内の画像ファイルを収集し、一つのPDFファイルに変換します。<br>変換されたPDFファイルがフォルダー内に保存されます。</p>



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



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



<p>このスクリプトを使用することで、フォルダー内の画像ファイルを簡単にPDFに変換できます。</p>



<p>PDFにすることで、ファイル管理や共有が簡単になり、様々なデバイスで一貫した表示が可能です。Pythonのライブラリを活用することで、画像処理やファイル操作が効率的に行えます。</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/images-to-pdf/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】Tkinterのbindメソッドでイベント検出</title>
		<link>https://alicia-ing.com/programming/python/bind/</link>
					<comments>https://alicia-ing.com/programming/python/bind/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Fri, 15 Sep 2023 14:24:23 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=3495</guid>

					<description><![CDATA[TkinterはPythonの標準ライブラリに含まれているGUI（グラフィカルユーザーインターフェース）ツールです。 Tkinterはシンプルで使いやすく、設定画面、ファイル選択ダイアログなど小規模なアプリケーションを作 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>TkinterはPythonの<strong>標準ライブラリに含まれているGUI</strong>（グラフィカルユーザーインターフェース）ツールです。</p>



<p>Tkinterはシンプルで使いやすく、設定画面、ファイル選択ダイアログなど<strong>小規模なアプリケーションを作成するのに適しています。</strong></p>



<p>一方で、ボタンやテキストボックスなど簡易的なウィジェットばかりで<strong>大規模なアプリを作成することにはあまり適していない</strong>です。</p>



<p>しかし<strong>bindメソッドを使用</strong>すれば、Tkinterウィンドウをキーボードのキーやマウスクリック、カーソルを操作した時に<strong>処理をトリガーとして実行</strong>することができます。</p>



<p>本記事では、bindメソッドを使い方を紹介します。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>Pythonでデスクトップアプリケーションを作れるようになりたい</li>



<li>bindメソッドの使い方を知りたい</li>



<li>Pythonで画像トリミングする方法を知りたい</li>
</ul>
</div></div>



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="3495" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">bind：Tkinter</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-2">bindメソッドのイベントハンドラ</a></li><li class="rtoc-item"><a href="#rtoc-3">カスタムイベント</a></li><li class="rtoc-item"><a href="#rtoc-4">動的な制御</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-5">bind一覧</a></li><li class="rtoc-item"><a href="#rtoc-6">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">bind：Tkinter</h2>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1980" height="1020" src="https://alicia-ing.com/wp-content/uploads/2023/10/bind-method.webp" alt="" class="wp-image-3701" style="object-fit:cover" srcset="https://alicia-ing.com/wp-content/uploads/2023/10/bind-method.webp 1980w, https://alicia-ing.com/wp-content/uploads/2023/10/bind-method-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/10/bind-method-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/10/bind-method-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2023/10/bind-method-1536x791.webp 1536w" sizes="(max-width: 1980px) 100vw, 1980px" /></figure>



<p>Pythonにおけるbindは、Tkinterにおけるbind（GUIイベントの結びつけ）とソケット（socket）における bind（IPとポートを結びつける）２つあります。</p>



<p>本記事では、<strong>ウィジェットにイベントハンドラを関連付ける</strong>bindメソッドを使用します。</p>



<p>具体的にbindメソッドを使用すれば、ユーザーがボタンクリックやキーボード、マウスを操作した際にそれに応じた動作したり、<strong>カスタムイベント</strong>を作成して<strong>アクションを実行</strong>したりできます。</p>



<p>また、特定の条件が満たされたときにボタンを無効化、有効化にするような<strong>動的な制御</strong>ができます。</p>



<h3 id="rtoc-2"  class="wp-block-heading">bindメソッドのイベントハンドラ</h3>



<p>初めにイベントハンドラについて。</p>



<p>イベントハンドラとは、特定のイベントが発生した時に実行するよう定められた処理のことです。一般的にイベントを一対一に処理を結び付けたものをハンドラ、一つのイベントに対して複数の処理を結び付けたものをリスナといいます。</p>



<p>参考：「<a target="_self" title="イベントハンドラ（イベントリスナ）とは" href="https://e-words.jp/w/%E3%82%A4%E3%83%99%E3%83%B3%E3%83%88%E3%83%8F%E3%83%B3%E3%83%89%E3%83%A9.html">イベントハンドラ（イベントリスナ）とは</a>」</p>



<p>ユーザーによる処理の例として、ボタンクリックをします。</p>



<p>ボタンクリックはdefで定義した処理をボタンの<strong>commandに紐づけて実行</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 Button(ボタン)の使い方と関数処理を解説しています。</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>上記の記事で紹介したスクリプトを参考にして、ボタンを押すとターミナルに「アリッシアの朝」と表示するようにしました。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>#クリックしたときに実行する関数
def button_click():
    print(&quot;アリッシアの朝&quot;)

#ボタンを作成
button = tkinter.Button(root, text=&quot;Click&quot;, command=button_click)
button.pack()</code></pre></div>



<p>実行結果は以下のようになります。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1920" height="900" src="https://alicia-ing.com/wp-content/uploads/2023/09/Simulation01.gif" alt="" class="wp-image-8722"/></figure>



<p>bindメソッドで<strong>commandオプションと同じ処理</strong>をするには、コードを以下のように書き換えます。</p>



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

def button_click(event):
    print(&quot;アリッシアの朝&quot;) 

root = tkinter.Tk()
button = tkinter.Button(root, text=&quot;Click&quot;)
button.pack()

# ボタンがクリックされたときに関数 on_button_click を呼び出す
button.bind(&quot;&lt;Button-1&gt;&quot;, button_click)

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



<p>実行結果は先ほどと同じで、<strong>ボタンとクリックするとウィジェットにイベントハンドラを関連付けられて文字が出力</strong>されます。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1920" height="900" src="https://alicia-ing.com/wp-content/uploads/2023/09/Simulation02.gif" alt="" class="wp-image-8723"/></figure>



<h3 id="rtoc-3"  class="wp-block-heading">カスタムイベント</h3>



<p>カスタムイベントは、イベント駆動型プログラミングの一部として使用されて、<br><strong>特定の条件やユーザーの操作に応答するためにプログラム内で定義</strong>します。</p>



<p>主に、プログラムの複雑性を管理、特定のタスクやイベントを追跡に役立ちます。</p>



<p>先ほど、使用した<strong>&lt;Button-1&gt;</strong>は左クリックを意味しています。<br>そこに<strong>コントロールキーを押しながら左クリックをすると処理</strong>されるようにするには、コードを次のようにします。</p>



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

def custom_event(event):
    print(&quot;アリッシアの朝&quot;)

def left_click(event):
    if event.state == 4:  # Controlキー
        root.event_generate(&quot;&lt;&lt;CustomEvent&gt;&gt;&quot;)

root = tkinter.Tk()

# カスタムイベントを定義
root.event_add(&quot;&lt;&lt;CustomEvent&gt;&gt;&quot;, &quot;&lt;Button-1&gt;&quot;)

# カスタムイベントとハンドラを関連付け
root.bind(&quot;&lt;&lt;CustomEvent&gt;&gt;&quot;, custom_event)

# 左クリックイベントを監視
root.bind(&quot;&lt;Button-1&gt;&quot;, left_click)

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



<p>left_click 関数は、左クリックイベントが発生したときに実行されるイベントハンドラです。<br>この関数では、<strong>Controlキーが押されている場合にのみ &lt;&gt; カスタムイベント</strong>を発生させるように設定します。</p>



<p>root.event_add(&#8220;&lt;&gt;&#8221;, &#8220;&#8221;) を使用して、&lt;&gt; というカスタムイベントを定義し、<strong>左クリックイベント と関連付けます。</strong></p>



<p>root.bind(&#8220;&lt;&gt;&#8221;, custom_event) により、カスタムイベントと custom_event 関数を関連付けます。つまり、<strong>カスタムイベントがトリガーされると、custom_event関数が実行</strong>します。</p>



<p>root.bind(&#8220;&#8221;, left_click) により、左クリックイベントとleft_click関数を関連付けます。<br><strong>左クリックが発生した場合、left_click 関数が実行</strong>されます。</p>



<p>スクリプトを実行すると、コントロールキーを押しながら左クリックすると、文字が表示されます。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1700" height="900" src="https://alicia-ing.com/wp-content/uploads/2023/09/Simulation03.gif" alt="" class="wp-image-8724"/></figure>



<h3 id="rtoc-4"  class="wp-block-heading">動的な制御</h3>



<p>ボタンを押すと文字が出てきて、もう一度押すとテキストが変化します。<br><strong>さらにボタンを押下すると元のテキストに戻る操作</strong>をします。</p>



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

def toggle_text(event):
    if label.cget(&quot;text&quot;) == &quot;こんにちは&quot;:
        new_text = &quot;ありがとう&quot;
    else:
        new_text = &quot;こんにちは&quot;
    label.config(text=new_text)

root = tkinter.Tk()

label = tkinter.Label(root)
label.pack(pady=20)

button = tkinter.Button(root, text=&quot;Click&quot;)
button.pack()

# ボタンにクリックイベントとイベントハンドラを関連付け
button.bind(&quot;&lt;Button-1&gt;&quot;, toggle_text)

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



<p>このスクリプトを実行すると、テキストが切り替わります。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1920" height="900" src="https://alicia-ing.com/wp-content/uploads/2023/09/Simulation04.gif" alt="" class="wp-image-8725"/></figure>



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



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



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



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



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



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



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



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



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



<h2 id="rtoc-5"  class="wp-block-heading">bind一覧</h2>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1980" height="1020" src="https://alicia-ing.com/wp-content/uploads/2023/10/event-list.webp" alt="" class="wp-image-3700" srcset="https://alicia-ing.com/wp-content/uploads/2023/10/event-list.webp 1980w, https://alicia-ing.com/wp-content/uploads/2023/10/event-list-300x155.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/10/event-list-1024x528.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/10/event-list-768x396.webp 768w, https://alicia-ing.com/wp-content/uploads/2023/10/event-list-1536x791.webp 1536w" sizes="(max-width: 1980px) 100vw, 1980px" /></figure>



<p>bindメソッドで使用可能なイベントは以下の通りです。</p>



<p>表では-1を例にしています。</p>



<p><strong>-1は左クリック、-2：ホイールクリック、-3：右クリック</strong>と変更ができます。</p>



<figure class="wp-block-table alignfull"><div class="scrollable-table"><table><tbody><tr><td class="has-text-align-center" data-align="center">イベント</td><td class="has-text-align-center" data-align="center">処理</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Button-1&gt;・&lt;1&gt;・&lt;ButtonPress&gt;</td><td class="has-text-align-center" data-align="center">マウスの左クリック</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;ButtonRelease-1&gt;</td><td class="has-text-align-center" data-align="center">マウスの左クリック離したとき</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Double-1&gt;</td><td class="has-text-align-center" data-align="center">マウスの左をダブルクリック</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;KeyPress&gt;、&lt;KeyRelease&gt;</td><td class="has-text-align-center" data-align="center">キー入力、キー離したとき</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;KeyPress-A&gt;、&lt;a&gt;</td><td class="has-text-align-center" data-align="center">aキー入力</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Control&gt;</td><td class="has-text-align-center" data-align="center">ctrlキー入力</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Control-c&gt;</td><td class="has-text-align-center" data-align="center">ctrlキーとcキー同時入力</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;FocusIn&gt;、&lt;FocusOut&gt;</td><td class="has-text-align-center" data-align="center">ウィジェットがフォーカスを取得したとき、失ったとき</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Configure&gt;</td><td class="has-text-align-center" data-align="center">ウィジェットのサイズが変更されたとき</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Destroy&gt;</td><td class="has-text-align-center" data-align="center">ウィジェットが閉じられるとき</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Enter&gt;</td><td class="has-text-align-center" data-align="center">マウスカーソルがウィジェットに入ったとき</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Leave&gt;</td><td class="has-text-align-center" data-align="center">マウスカーソルがウィジェットから出たとき</td></tr><tr><td class="has-text-align-center" data-align="center">&lt;Motion&gt;</td><td class="has-text-align-center" data-align="center">マウスカーソルがウィジェットで動いたとき</td></tr></tbody></table></div></figure>



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



<p>Tkinterはシンプルで使いやすいですが、簡易的なウィジェットばかりなので小規模なアプリケーションを作成するのに適しています。</p>



<p>しかし、bindメソッドを使用すれば、Tkinterウィンドウをキーボードのキーやマウスクリック、カーソルを操作した時に処理を実行することができます。</p>



<p>bindメソッドは、ウィジェットにイベントハンドラを関連付けるために使用されます。</p>



<p>bindメソッドを使用すれば、ユーザーインタラクション、カスタムイベント、<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/bind/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>【Python】 統計処理・データ分析で必要なライブラリ一覧</title>
		<link>https://alicia-ing.com/programming/python/statpy-library/</link>
					<comments>https://alicia-ing.com/programming/python/statpy-library/#respond</comments>
		
		<dc:creator><![CDATA[アリッシア]]></dc:creator>
		<pubDate>Sun, 07 May 2023 09:43:49 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Tkinter]]></category>
		<guid isPermaLink="false">https://alicia-ing.com/?p=1484</guid>

					<description><![CDATA[Pythonで理解する統計学、第0回は、統計解析・データ分析（データサイエンス）などで使うライブラリの紹介です。 Pythonにはあらかじめ書かれた関数、メソッド、クラス、および変数などプログラムを簡単かつ効率的に書くこ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Pythonで理解する統計学、第0回は、統計解析・データ分析（データサイエンス）などで使うライブラリの紹介です。</p>



<p>Pythonにはあらかじめ書かれた関数、メソッド、クラス、および変数などプログラムを簡単かつ効率的に書くことができるように設計されたライブラリが存在します。</p>



<p>本記事で紹介するライブラリはpipと呼ばれるパッケージマネージャを使用してインストールできます。</p>



<p>また、「<strong>Google Colaboratory</strong>」のようなクラウド上でPython開発環境を動作させるサービスは紹介するライブラリは搭載済みなので、インストールは不要です。</p>



<p>さらに、Tkinterと併用することで、アプリ化することも可能であり、ユーザーの数値入力によってグラフをプロットすることもできます。</p>



<div class="wp-block-cocoon-blocks-label-box-1 label-box block-box cocoon-block-label-box"><div class="label-box-label block-box-label box-label fab-check"><span class="label-box-label-text block-box-label-text box-label-text">本記事は次の人におすすめ</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>Numpy・Matplotlib・Pandas・Scipyライブラリの使い方を知りたい</li>



<li>Google Colaboratoryについて知りたい</li>
</ul>
</div></div>



<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-folder"><span class="label-box-label-text block-box-label-text box-label-text">関連記事</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li><a target="_self" href="https://alicia-ing.com/programming/python/statistics-mean-var-stdev-median-mode/">平均・分散・標準偏差を表現</a></li>
</ul>
</div></div>



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



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



<div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset1 animation-none rtoc_open default" data-id="1484" data-theme="Cocoon Child">
			<div id="rtoc-mokuji-title" class=" rtoc_left">
			<button class="rtoc_open_close rtoc_open"></button>
			<span>目次</span>
			</div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1">Numpy</a></li><li class="rtoc-item"><a href="#rtoc-2">Matplotlib</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-3">折れ線グラフ</a></li><li class="rtoc-item"><a href="#rtoc-4">散布図</a></li><li class="rtoc-item"><a href="#rtoc-5">棒グラフ</a></li><li class="rtoc-item"><a href="#rtoc-6">ヒストグラム</a></li><li class="rtoc-item"><a href="#rtoc-7">等高線図</a></li><li class="rtoc-item"><a href="#rtoc-8">3Dプロット</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-9">Pandas</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-10">Excelのテストの点数をPythonでグラフ化</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-11">Scipy</a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-12">最小二乗法による回帰分析</a></li><li class="rtoc-item"><a href="#rtoc-13">フーリエ変換による信号の周波数解析</a></li><li class="rtoc-item"><a href="#rtoc-14">離散コサイン変換による画像圧縮</a></li><li class="rtoc-item"><a href="#rtoc-15">積分による確率分布関数の計算</a></li></ul></li><li class="rtoc-item"><a href="#rtoc-16">Jupyter・Google Colaboratory</a></li><li class="rtoc-item"><a href="#rtoc-17">まとめ</a></li></ol></div><h2 id="rtoc-1"  class="wp-block-heading">Numpy</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="533" src="https://alicia-ing.com/wp-content/uploads/2023/05/Numpy_0000-1024x533.webp" alt="Numpyについて" class="wp-image-2061" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/Numpy_0000-1024x533.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/05/Numpy_0000-300x156.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/05/Numpy_0000-768x400.webp 768w, https://alicia-ing.com/wp-content/uploads/2023/05/Numpy_0000-1536x800.webp 1536w, https://alicia-ing.com/wp-content/uploads/2023/05/Numpy_0000.webp 1920w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p><strong>NumPy</strong>は、&#8221;Numerical（数値）Python&#8221;の略で、科学的計算やデータ解析を行うための<strong>数値計算</strong>ライブラリで、大規模な数値計算や<strong>行列演算、信号処理、画像処理、機械学習</strong>などの科学技術計算を行うことができます。</p>



<p><strong>NumPy</strong>は、科学技術計算でよく使用される数学関数、線形代数関数、フーリエ変換、ランダム数生成などの豊富な数学関数を提供しています。また、後述するライブラリやフレームワーク（pandas・ Matplotlibなど）と組み合わせて使用されることが多いです。</p>



<p>公式サイト：「<a target="_self" href="https://numpy.org/" title="Numpy">Numpy</a>」</p>



<h2 id="rtoc-2"  class="wp-block-heading">Matplotlib</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="533" src="https://alicia-ing.com/wp-content/uploads/2023/05/Matplotlib_0000-1024x533.webp" alt="Matplotlibについて" class="wp-image-2062" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/Matplotlib_0000-1024x533.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/05/Matplotlib_0000-300x156.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/05/Matplotlib_0000-768x400.webp 768w, https://alicia-ing.com/wp-content/uploads/2023/05/Matplotlib_0000-1536x800.webp 1536w, https://alicia-ing.com/wp-content/uploads/2023/05/Matplotlib_0000.webp 1920w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Matplotlibは、Pythonの<strong>データ可視化</strong>ライブラリの1つであり、様々なグラフや図を作成することができます。グラフや図の種類は<strong>折れ線グラフ、散布図、棒グラフ、ヒストグラム、等高線図、3Dプロット</strong>と手広く扱うことができます。</p>



<p>公式サイト：「<a target="_self" href="https://matplotlib.org/" title="Matplotlib — Visualization with Python">Matplotlib — Visualization with Python</a>」</p>



<p>タイトルや凡例（軸の名前）などのグラフのカスタマイズは次のように書きます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>plt.title(&#39;タイトル&#39;)
plt.xlabel(&#39;定義域（X軸）の凡例&#39;)
plt.ylabel(&#39;値域（y軸）の凡例&#39;)</code></pre></div>



<p>また、グラフを出力するには次のように書きます。<br>MatplotlibはPNG形式の他にも、JPEG、PDF、SVGなど多くの形式に対応しています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-plain"><code>plt.savefig(&#39;ファイル名.png&#39;)</code></pre></div>



<p>その他、前述したNumPyとの統合も容易であり、<br><strong>NumPyの配列を用いてグラフ</strong>を作成することができます。</p>



<p>以下は、紹介したグラフや図の出力です。</p>



<h3 id="rtoc-3"  class="wp-block-heading">折れ線グラフ</h3>



<p>折れ線グラフは、<strong>データの連続的な変化</strong>を示すのに適しています。そのため、時間経過に伴うデータの変化を示すのによく使われます。また、複数のデータ系列を比較するのにも適しています。</p>



<p>折れ線グラフは、<strong>値の変化が滑らかであることが重要</strong>であるため、<strong>離散的なデータ</strong>では使用することができません。</p>



<p>離散的なデータ代表例は、テストの点数や「はい・いいえ」のような選択性アンケートなど整数値やカテゴリーなどです。<br>このようなデータを扱うときは、後述する棒グラフが優れています。</p>



<p>折れ線グラフのソースコードでは、sin関数の表現を紹介します。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import matplotlib.pyplot as plt
import numpy as np
# 折れ線グラフ
x = np.arange(0, 10, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.title(&#39;Sin Wave&#39;)
plt.xlabel(&#39;x&#39;)
plt.ylabel(&#39;y&#39;)
plt.savefig(&#39;line_graph_plot.png&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/line_graph_plot.webp" alt="sin関数" class="wp-image-2063" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/line_graph_plot.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/line_graph_plot-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-4"  class="wp-block-heading">散布図</h3>



<p>散布図は、<strong>2つの量的なデータの相関関係を視覚化</strong>するのに適しています。例えば、身長が高いと体重が重いのか（身長と体重の関係）、気温が高いとアイスクリームが売れるのか（気温とアイスクリームの販売数）の関係などが挙げられます。</p>



<p>散布図は、<strong>横軸と縦軸に2つの変数</strong>をとり、各変数の値を点としてプロットします。各点は、2つの変数の値を示し、データがどのように散らばっているかを確認することができます。</p>



<p>散布図を使用することで、相関関係があるかどうか、強さや方向性などを簡単に判断することができます。また、<strong>散布図に回帰直線を追加</strong>することで、2つの変数の関係をより詳しく調べることができます。</p>



<p>散布図は、統計解析や機械学習、ビジネス、科学などの多くの分野で広く使用されています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import matplotlib.pyplot as plt
import numpy as np
# 散布図
x = np.random.normal(0, 1, 100)
y = np.random.normal(0, 1, 100)
plt.scatter(x, y)
plt.title(&#39;Scatter Plot&#39;)
plt.xlabel(&#39;x&#39;)
plt.ylabel(&#39;y&#39;)
plt.savefig(&#39;scatter_plot.png&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/scatter_plot.webp" alt="散布図" class="wp-image-2065" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/scatter_plot.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/scatter_plot-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-5"  class="wp-block-heading">棒グラフ</h3>



<p>棒グラフは、カテゴリーごとの値の比較や分布など<strong>離散的なデータ</strong>を視覚的に表現するのに適しています。例えば、各都道府県の人口、各商品の売上、各月の降水量など、カテゴリーが限られているデータを表現するのに適しています。</p>



<p>棒グラフは、<strong>縦軸に数値を、横軸にカテゴリー</strong>をとり、それぞれのカテゴリーごとに棒を立てて表現します。棒の高さが数値を表し、カテゴリー間の棒の長さや厚さが比較の基準となります。</p>



<p>棒グラフを使用することで、カテゴリーごとの数値の大小関係や、分布の傾向などを簡単に判断することができます。また、複数の棒グラフを比較することで、<strong>データの変化や傾向を把握</strong>することができます。</p>



<p>棒グラフは、統計解析やビジネスのほか社会調査などの分野で広く使用されています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import matplotlib.pyplot as plt
import numpy as np
# 棒グラフ
labels = [&#39;Apple&#39;, &#39;Banana&#39;, &#39;Orange&#39;]
values = [20, 35, 25]
plt.bar(labels, values)
plt.title(&#39;Fruit Sales&#39;)
plt.xlabel(&#39;Fruit&#39;)
plt.ylabel(&#39;Sales&#39;)
plt.savefig(&#39;bar_graph_plot.png&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/bar_graph_plot.webp" alt="棒グラフ" class="wp-image-2066" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/bar_graph_plot.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/bar_graph_plot-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-6"  class="wp-block-heading">ヒストグラム</h3>



<p>ヒストグラムは、<strong>数値データの分布</strong>を視覚化するために使用されます。例えば、身長や体重の分布、テストの点数の分布、経済的な指標の分布など、<strong>数値データの特徴を把握</strong>するのに適しています。</p>



<p>ヒストグラムは、<strong>横軸にデータの値の範囲を、縦軸にその範囲内にあるデータの個数や頻度</strong>をとり、各値の頻度を棒で表現します。<strong>各棒の高さが頻度</strong>を表し、横軸の範囲に対して棒の幅が設定されることがあります。</p>



<p>ヒストグラムを使用することで、<strong>データの分布の形状</strong>や<strong>平均値</strong>、<strong>分散</strong>などの統計的な特徴を簡単に把握することができます。また、複数のヒストグラムを比較することで、データの傾向や特徴を把握することができます。</p>



<p>ヒストグラムは、統計解析や機械学習、科学、ビジネスなどの分野で広く使用されています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import matplotlib.pyplot as plt
import numpy as np
# ヒストグラム
data = np.random.normal(0, 1, 1000)
plt.hist(data, bins=30)
plt.title(&#39;Histogram&#39;)
plt.xlabel(&#39;Value&#39;)
plt.ylabel(&#39;Frequency&#39;)
plt.savefig(&#39;histogram.png&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/histogram.webp" alt="ヒストグラム" class="wp-image-2067" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/histogram.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/histogram-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-7"  class="wp-block-heading">等高線図</h3>



<p>等高線図は、<strong>2つの数値変数の関係を表現</strong>するグラフの一つで、<strong>3次元のデータを平面上に投影して、等高線状の線で表現</strong>します。例えば、高度と気温、海面水位と陸地の高さ、座標と気温など、2つの変数の関係を表現するのに適しています。</p>



<p>等高線図は、<strong>縦軸と横軸に2つの変数を、等高線で高さを表現</strong>します。各等高線は、同じ高さの地点を結んだ線で、<strong>高さが高いところほど密集</strong>していて、<strong>低いところほど疎</strong>になっています。また、等高線の間隔は、高低差に応じて調整され、等高線の密集度が高いところは急峻な地形、疎になっているところは平坦な地形を表します。</p>



<p>等高線図を使用することで、<strong>2つの変数の関係を視覚化</strong>し、それぞれの変数の影響を理解することができます。また、異なる高度や温度の地点の分布や傾向を把握することができます。</p>



<p>等高線図は、気象学や地理学、物理学、工学などの分野で広く使用されています。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import matplotlib.pyplot as plt
import numpy as np
# 等高線図
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
plt.contourf(X, Y, Z)
plt.colorbar()
plt.title(&#39;Contour Plot&#39;)
plt.xlabel(&#39;x&#39;)
plt.ylabel(&#39;y&#39;)
plt.savefig(&#39;contour_plot.png&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/contour_plot.webp" alt="等高線" class="wp-image-2068" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/contour_plot.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/contour_plot-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-8"  class="wp-block-heading">3Dプロット</h3>



<p>3Dプロットは、<strong>3つの数値変数を使用して、立体的なグラフを作成</strong>するための手法です。例えば、2つの変数によって表される平面上での関係に加えて、3つ目の変数を追加して、立体的な関係を表現することができます。例えば、気温、風速、湿度など、3つの変数によって表される関係を表現するのに適しています。</p>



<p>3Dプロットは、3つの変数を<strong>縦軸、横軸、深度軸</strong>に割り当てて、3Dグラフを作成します。各点の座標は、3つの変数の値を表し、点の色やサイズなどを調整することで、さらに多様な情報を表現することができます。</p>



<p>3Dプロットを使用することで、3つの変数の関係を立体的に表現し、その変数同士の相関や傾向を把握することができます。また、<strong>多変量データの可視化に有効な手法</strong>であり、データの特徴や傾向を理解することができます。</p>



<p>3Dプロットは、科学や工学、ビジネスなど、多くの分野で使用されています。しかし、複雑なデータを扱う場合は、データの解釈が難しくなる場合があるため、注意が必要です。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 3Dプロット
fig = plt.figure()
ax = fig.add_subplot(111, projection=&#39;3d&#39;)
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
ax.plot_surface(X, Y, Z)
ax.set_title(&#39;3D Surface Plot&#39;)
ax.set_xlabel(&#39;x&#39;)
ax.set_ylabel(&#39;y&#39;)
ax.set_zlabel(&#39;z&#39;)
plt.savefig(&#39;3d_surface_plot.png&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/3d_surface_plot.webp" alt="3D図" class="wp-image-2069" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/3d_surface_plot.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/3d_surface_plot-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h2 id="rtoc-9"  class="wp-block-heading">Pandas</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="533" src="https://alicia-ing.com/wp-content/uploads/2023/05/Pandas_0000-1024x533.webp" alt="pandasについて" class="wp-image-2082" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/Pandas_0000-1024x533.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/05/Pandas_0000-300x156.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/05/Pandas_0000-768x400.webp 768w, https://alicia-ing.com/wp-content/uploads/2023/05/Pandas_0000-1536x800.webp 1536w, https://alicia-ing.com/wp-content/uploads/2023/05/Pandas_0000.webp 1920w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Pandasは、Pythonで使われるオープンソースの<strong>データ解析ライブラリ</strong>です。Pandasは、NumPyの上に構築されており、より高水準のデータ操作機能を提供しています。主に、<strong>データフレームとシリーズの2つのデータ構造</strong>を提供しています。</p>



<p>データフレームは、2次元のラベル付きデータ構造で、列ごとに異なるデータ型を持つことができます。データフレームを用いることで、<strong>データの整形、加工、結合、集計、欠損値の処理</strong>など、様々なデータ処理を簡単に行うことができます。<br><strong>データの読み込みや書き出しにも対応</strong>しており、CSV、Excel、SQL、JSON、HTML、XML、Parquetなどの様々な形式を扱うことができます。</p>



<p>シリーズは、1次元のラベル付きデータ構造で、NumPyの配列に似たデータ型を持ちます。シリーズは、データフレームの列または行として使用することができます。</p>



<p>Pandasは、データ処理に必要な機能を多数提供しており、データのクリーニング、変換、集計、可視化、機械学習など、様々なタスクを実行することができます。</p>



<p>Pandasは、金融、ビジネス、科学、技術、社会科学など、多くの分野で使用されています。</p>



<p>公式サイト:「<a target="_self" href="https://pandas.pydata.org/" title="pandas - Python Data Analysis Library">pandas &#8211; Python Data Analysis Library</a>」</p>



<h3 id="rtoc-10"  class="wp-block-heading">Excelのテストの点数をPythonでグラフ化</h3>



<p>Pandasを使って、Excelに入力された10点満点のテストの得点分布をヒストグラムに表示します。</p>



<p>以下の画像のようにAさんからZさん計26人のテスト点数を用意します。</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="1126" height="1000" src="https://alicia-ing.com/wp-content/uploads/2023/05/excel-1.webp" alt="扱うデータ" class="wp-image-7710" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/excel-1.webp 1126w, https://alicia-ing.com/wp-content/uploads/2023/05/excel-1-300x266.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/05/excel-1-1024x909.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/05/excel-1-768x682.webp 768w" sizes="(max-width: 1126px) 100vw, 1126px" /></figure>



<p>Excelのファイル(data.xlsx)は<strong>パスを指定</strong>するか、<strong>同じ場所に設置</strong>する必要があります。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Excelファイルの読み込み
df = pd.read_excel(&#39;data.xlsx&#39;, sheet_name=&#39;Sheet1&#39;)
# 得点の配列を作成
scores = np.array(df[&#39;点数&#39;])
# ヒストグラムの描画
plt.hist(scores, bins=10, range=(0, 10), alpha=0.5)
plt.xlabel(&#39;Points&#39;)
plt.ylabel(&#39;people&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/Excel.webp" alt="棒グラフ" class="wp-image-2070" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/Excel.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/Excel-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h2 id="rtoc-11"  class="wp-block-heading">Scipy</h2>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="533" src="https://alicia-ing.com/wp-content/uploads/2023/05/Scipy_0000-1024x533.webp" alt="scipyについて" class="wp-image-2083" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/Scipy_0000-1024x533.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/05/Scipy_0000-300x156.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/05/Scipy_0000-768x400.webp 768w, https://alicia-ing.com/wp-content/uploads/2023/05/Scipy_0000-1536x800.webp 1536w, https://alicia-ing.com/wp-content/uploads/2023/05/Scipy_0000.webp 1920w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>Scipyは、科学技術計算において必要な<strong>数学的なアルゴリズムや関数を提供</strong>するPythonのライブラリです。NumPyをベースにしており、多くのサブパッケージを含んでいます。</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-pencil"><span class="label-box-label-text block-box-label-text box-label-text">Scipyの主な計算機能</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>線形代数</li>



<li>統計処理</li>



<li>最適化(Nelder-Mead法、BFGS法、Newton法、Levenberg-Marquardt法 etc.)</li>



<li>信号処理</li>



<li>画像処理</li>



<li>離散フーリエ変換</li>



<li>微分方程式の解法</li>



<li>積分の数値計算</li>



<li>特殊関数（ベータ関数、ガンマ関数、ベッセル関数、超幾何関数、楕円積分 etc.）の計算</li>
</ul>
</div></div>



<p><br>このように、Scipyは、科学技術計算に必要な高度な数学的なアルゴリズムを使用できるため、機械学習・データ分析・信号処理・画像処理などの分野で広く使用されています。</p>



<p>公式サイト：「<a target="_self" href="https://scipy.org/" title="SciPy">SciPy</a>」</p>



<p>例えば、以下のようなScipyの機能があります。</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-pencil"><span class="label-box-label-text block-box-label-text box-label-text">Scipyを使う場面</span></div><div class="label-box-content block-box-content box-content">
<ul class="wp-block-list">
<li>最小二乗法による回帰分析</li>



<li>フーリエ変換による信号の周波数解析</li>



<li>離散コサイン変換による画像圧縮</li>



<li>積分による確率分布関数の計算</li>
</ul>
</div></div>



<p><br>以下に、Scipyを使った解析や計算を紹介します。</p>



<h3 id="rtoc-12"  class="wp-block-heading">最小二乗法による回帰分析</h3>



<p>最小二乗法による回帰分析は、<strong>2つの変数間の関係を調べる</strong>際によく使われます。例えば、身長と体重の関係を調べたり、気温とエアコンの使用量の関係を調べたりすることができます。</p>



<p>最小二乗法による回帰分析は、変数間の線形関係をモデル化して、そのモデルを用いて予測を行うことができます。また、回帰分析の結果から、<strong>変数間の関係の強さや方向性を評価</strong>することができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# 最小二乗法による回帰分析
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 3, 5, 6, 8])
def func(x, a, b):
    return a * x + b
popt, pcov = curve_fit(func, x, y)
plt.scatter(x, y)
plt.plot(x, func(x, *popt), &#39;r&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/regression-analysis.webp" alt="最小二乗法" class="wp-image-2071" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/regression-analysis.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/regression-analysis-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-13"  class="wp-block-heading">フーリエ変換による信号の周波数解析</h3>



<p>フーリエ変換による信号の周波数解析は、<strong>信号処理や音声処理、画像処理などの分野</strong>でよく使われます。</p>



<p>信号処理（波形解析）において、フーリエ変換を用いて信号の周波数成分を解析することができます。</p>



<p>音声処理においては、音声ファイルを周波数成分に分解して、特定の周波数帯域の音声を取り出すことができます。</p>



<p>画像処理においては、フーリエ変換を用いて画像を周波数成分に分解して、特定の周波数帯域の画像情報を取り出したり、画像のフィルタリングを行ったりすることができます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft
# フーリエ変換による信号の周波数解析
N = 1000
T = 1.0 / 800.0
x = np.linspace(0.0, N * T, N)
y = np.sin(50.0 * 2.0 * np.pi * x) + 0.5 * np.sin(80.0 * 2.0 * np.pi * x)
yf = fft(y)
xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
plt.plot(xf, 2.0 / N * np.abs(yf[0:N // 2]))
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/frequency-analysis.webp" alt="フーリエ変換" class="wp-image-2072" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/frequency-analysis.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/frequency-analysis-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-14"  class="wp-block-heading">離散コサイン変換による画像圧縮</h3>



<p>離散コサイン変換は、<strong>画像の圧縮やデータ圧縮</strong>に使用されます。</p>



<p>一般的に、画像の圧縮には、JPEGなどの標準的なフォーマットが使用されています。</p>



<p>JPEGフォーマットでは、離散コサイン変換が信号を周波数成分に分解して、高周波成分を除去することで、効率的に圧縮されます。また、データ圧縮の分野でも、離散コサイン変換がよく使用されます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import dct, idct
from scipy.misc import face
# 離散コサイン変換による画像圧縮
img = face(gray=True).astype(&#39;float&#39;)
img_dct = dct(dct(img.T, norm=&#39;ortho&#39;).T, norm=&#39;ortho&#39;)
coef = 0.1
mask = np.where(np.abs(img_dct) &lt; coef, 0, 1)
img_dct *= mask
img_compressed = idct(idct(img_dct.T, norm=&#39;ortho&#39;).T, norm=&#39;ortho&#39;)
plt.imshow(img_compressed, cmap=&#39;gray&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/image-compression.webp" alt="離散コサイン変換" class="wp-image-2073" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/image-compression.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/image-compression-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



<h3 id="rtoc-15"  class="wp-block-heading">積分による確率分布関数の計算</h3>



<p>積分による確率分布関数の計算は、<strong>確率変数の値がある範囲に入る確率を求めたい場合</strong>に使用されます。</p>



<p>例えば、ある連続確率分布に従う確率変数Xが与えられた場合、その確率分布関数を積分することによって、Xがある範囲[a, b]に入る確率を求めることができます。</p>



<p>確率分布関数は、統計学や確率論などの分野でよく取り扱われます。</p>



<div class="hcb_wrap"><pre class="prism undefined-numbers lang-python" data-lang="Python"><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import quad
# 積分による確率分布関数の計算
def integrand(x):
    return np.exp(-x ** 2 / 2)
result= quad(integrand, -np.inf, np.inf)
x = np.linspace(-5, 5, 1000)
y = integrand(x)
plt.plot(x, y)
plt.title(&#39;Gaussian Distribution&#39;)
plt.xlabel(&#39;x&#39;)
plt.ylabel(&#39;Density&#39;)
plt.show()</code></pre></div>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="640" height="480" src="https://alicia-ing.com/wp-content/uploads/2023/05/integrand.webp" alt="確率分布" class="wp-image-2074" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/integrand.webp 640w, https://alicia-ing.com/wp-content/uploads/2023/05/integrand-300x225.webp 300w" sizes="(max-width: 640px) 100vw, 640px" /></figure>



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



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



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



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



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



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



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



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



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



<h2 id="rtoc-16"  class="wp-block-heading">Jupyter・Google Colaboratory</h2>



<p>Google Colaboratoryは、Googleが提供していて、Jupyter Notebookをベースとしたクラウド上で動作するPython開発環境です。GPUやTPUなどの高速な計算リソースも無料で利用できるため、データ解析や機械学習など、プログラミングやデータ分析に適しています。</p>



<p>公式サイト：「<a target="_self" href="https://jupyter.org/" title="Jupyter">Jupyter</a>」・「<a target="_self" href="https://colab.research.google.com/?hl=ja" title="Google Colaboratory">Google Colaboratory</a>」</p>



<p>以下に、Google Colaboratoryを用いて、積分による確率分布関数の計算した様子を示します。</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="576" src="https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1-1024x576.webp" alt="Google Colaboratory" class="wp-image-2075" srcset="https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1-1024x576.webp 1024w, https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1-300x169.webp 300w, https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1-768x432.webp 768w, https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1-120x68.webp 120w, https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1-160x90.webp 160w, https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1-320x180.webp 320w, https://alicia-ing.com/wp-content/uploads/2023/05/google-colaboratory-1536x864-1.webp 1536w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



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



<p>今回は、統計解析・データ分析で使うライブラリを確認しました。</p>



<figure class="wp-block-table alignwide"><div class="scrollable-table"><table><tbody><tr><td class="has-text-align-center" data-align="center">ライブラリ</td><td class="has-text-align-center" data-align="center">用途</td></tr><tr><td class="has-text-align-center" data-align="center">Numpy</td><td class="has-text-align-center" data-align="center">数値計算</td></tr><tr><td class="has-text-align-center" data-align="center">Matplotlib</td><td class="has-text-align-center" data-align="center">グラフや図を作成</td></tr><tr><td class="has-text-align-center" data-align="center">Pandas</td><td class="has-text-align-center" data-align="center">データ解析(CSV、Excelなどの読み込みや書き出し)</td></tr><tr><td class="has-text-align-center" data-align="center">Scipy</td><td class="has-text-align-center" data-align="center">数学的なアルゴリズムや関数を提供</td></tr></tbody></table></div></figure>



<p>これら４つは、統計学で非常によく使います。大量のデータもまとめることができるので、非常に便利です。</p>



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



<div class="wp-block-cocoon-blocks-button-1 aligncenter button-block"><a target="_self" href="https://click.linksynergy.com/deeplink?id=IyOtUnEMtpw&amp;mid=47984&amp;murl=https%3A%2F%2Fwww.udemy.com%2Fcourses%2Fdevelopment%2F" class="btn btn-m btn-shine has-background has-light-green-background-color">Udemy 公式サイト</a></div>
]]></content:encoded>
					
					<wfw:commentRss>https://alicia-ing.com/programming/python/statpy-library/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
