初心者向け No.33

ログインフォーム

ユーザー名・パスワード入力フォームのサンプル。Entryのshow属性でパスワードを隠す方法を学びます。

🎯 難易度: ★☆☆ 📦 ライブラリ: tkinter(標準ライブラリ) ⏱️ 制作時間: 30〜90分

1. アプリ概要

ユーザー名・パスワード入力フォームのサンプル。Entryのshow属性でパスワードを隠す方法を学びます。

このアプリは基本カテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ) で、難易度は ★☆☆ です。

Pythonでは tkinter を使うことで、クロスプラットフォームなGUIアプリを簡単に作成できます。このアプリを通じて、ウィジェットの配置・イベント処理・データ管理など、GUI開発の実践的なスキルを習得できます。

ソースコードは完全な動作状態で提供しており、コピーしてそのまま実行できます。まずは実行して動作を確認し、その後コードを読んで仕組みを理解していきましょう。カスタマイズセクションでは機能拡張のアイデアも紹介しています。

GUIアプリ開発は、プログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。アプリを作ることで、変数・関数・クラス・イベント処理など、プログラミングの重要な概念が自然と身についていきます。このアプリをきっかけに、オリジナルアプリの開発にも挑戦してみてください。

2. 機能一覧

  • ログインフォームのメイン機能
  • 直感的なGUIインターフェース
  • 入力値のバリデーション
  • エラーハンドリング
  • 結果の見やすい表示
  • キーボードショートカット対応

3. 事前準備・環境

ℹ️
動作確認環境

Python 3.10 以上 / Windows・Mac・Linux すべて対応

以下の環境で動作確認しています。

  • Python 3.10 以上
  • OS: Windows 10/11・macOS 12+・Ubuntu 20.04+

4. 完全なソースコード

💡
コードのコピー方法

右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。

app33.py
import tkinter as tk
from tkinter import ttk, messagebox


class App33:
    """ログインフォーム"""

    # サンプルユーザー(実際のアプリではDBなどで管理)
    USERS = {
        "admin": "password123",
        "user1": "hello",
        "python": "guido",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("ログインフォーム")
        self.root.geometry("400x360")
        self.root.configure(bg="#f8f9fc")
        self.attempts = 0
        self.max_attempts = 3
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="ログインフォーム",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=40, pady=24)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # アイコン
        tk.Label(main_frame, text="🔐", font=("Segoe UI Emoji", 36),
                 bg="#f8f9fc").pack(pady=(0, 16))

        # フォーム
        form_frame = ttk.LabelFrame(main_frame, text="アカウント情報を入力", padding=14)
        form_frame.pack(fill=tk.X)

        tk.Label(form_frame, text="ユーザー名:").grid(row=0, column=0, sticky="w", pady=6)
        self.username_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12))
        self.username_entry.grid(row=0, column=1, padx=8, sticky="ew")

        tk.Label(form_frame, text="パスワード:").grid(row=1, column=0, sticky="w", pady=6)
        self.password_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12), show="●")
        self.password_entry.grid(row=1, column=1, padx=8, sticky="ew")
        self.password_entry.bind("<Return>", lambda e: self.login())

        # パスワード表示切替
        self.show_pw = tk.BooleanVar(value=False)
        ttk.Checkbutton(form_frame, text="パスワードを表示",
                        variable=self.show_pw,
                        command=self.toggle_pw).grid(row=2, column=1, sticky="w")
        form_frame.columnconfigure(1, weight=1)

        # ログインボタン
        tk.Button(main_frame, text="ログイン",
                  font=("Noto Sans JP", 13, "bold"),
                  bg="#3776ab", fg="white", activebackground="#2a5a8a",
                  relief=tk.FLAT, padx=20, pady=8,
                  command=self.login).pack(pady=14)

        self.status_label = tk.Label(main_frame, text="",
                                     bg="#f8f9fc", font=("Noto Sans JP", 11))
        self.status_label.pack()

        # ヒント
        tk.Label(main_frame, text="ヒント: ユーザー名「admin」パスワード「password123」",
                 bg="#f8f9fc", fg="#aaa", font=("Noto Sans JP", 9)).pack(pady=(8, 0))

    def toggle_pw(self):
        self.password_entry.config(show="" if self.show_pw.get() else "●")

    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get()

        if not username or not password:
            self.status_label.config(text="❗ ユーザー名とパスワードを入力してください", fg="#e67e22")
            return

        self.attempts += 1

        if username in self.USERS and self.USERS[username] == password:
            self.status_label.config(text=f"✅ ログイン成功!ようこそ、{username} さん!", fg="#27ae60")
            self.root.after(1500, self._show_welcome, username)
        else:
            remaining = self.max_attempts - self.attempts
            if remaining <= 0:
                self.status_label.config(text="🔒 試行回数オーバー。ロックされました", fg="#e74c3c")
                self.username_entry.config(state=tk.DISABLED)
                self.password_entry.config(state=tk.DISABLED)
            else:
                self.status_label.config(
                    text=f"❌ ユーザー名またはパスワードが違います(残り{remaining}回)", fg="#e74c3c")
            self.password_entry.delete(0, tk.END)

    def _show_welcome(self, username):
        for w in self.root.winfo_children():
            w.destroy()
        frame = tk.Frame(self.root, bg="#f8f9fc")
        frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
        tk.Label(frame, text="✅ ログイン成功",
                 font=("Noto Sans JP", 18, "bold"), bg="#f8f9fc", fg="#27ae60").pack(pady=(0, 12))
        tk.Label(frame, text=f"ようこそ、{username} さん!",
                 font=("Noto Sans JP", 14), bg="#f8f9fc").pack()
        ttk.Button(frame, text="ログアウト", command=self._logout).pack(pady=20)

    def _logout(self):
        for w in self.root.winfo_children():
            w.destroy()
        self.attempts = 0
        self._build_ui()


if __name__ == "__main__":
    root = tk.Tk()
    app = App33(root)
    root.mainloop()

5. コード解説

ログインフォームのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

クラス設計とコンストラクタ

App33クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。

import tkinter as tk
from tkinter import ttk, messagebox


class App33:
    """ログインフォーム"""

    # サンプルユーザー(実際のアプリではDBなどで管理)
    USERS = {
        "admin": "password123",
        "user1": "hello",
        "python": "guido",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("ログインフォーム")
        self.root.geometry("400x360")
        self.root.configure(bg="#f8f9fc")
        self.attempts = 0
        self.max_attempts = 3
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="ログインフォーム",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=40, pady=24)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # アイコン
        tk.Label(main_frame, text="🔐", font=("Segoe UI Emoji", 36),
                 bg="#f8f9fc").pack(pady=(0, 16))

        # フォーム
        form_frame = ttk.LabelFrame(main_frame, text="アカウント情報を入力", padding=14)
        form_frame.pack(fill=tk.X)

        tk.Label(form_frame, text="ユーザー名:").grid(row=0, column=0, sticky="w", pady=6)
        self.username_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12))
        self.username_entry.grid(row=0, column=1, padx=8, sticky="ew")

        tk.Label(form_frame, text="パスワード:").grid(row=1, column=0, sticky="w", pady=6)
        self.password_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12), show="●")
        self.password_entry.grid(row=1, column=1, padx=8, sticky="ew")
        self.password_entry.bind("<Return>", lambda e: self.login())

        # パスワード表示切替
        self.show_pw = tk.BooleanVar(value=False)
        ttk.Checkbutton(form_frame, text="パスワードを表示",
                        variable=self.show_pw,
                        command=self.toggle_pw).grid(row=2, column=1, sticky="w")
        form_frame.columnconfigure(1, weight=1)

        # ログインボタン
        tk.Button(main_frame, text="ログイン",
                  font=("Noto Sans JP", 13, "bold"),
                  bg="#3776ab", fg="white", activebackground="#2a5a8a",
                  relief=tk.FLAT, padx=20, pady=8,
                  command=self.login).pack(pady=14)

        self.status_label = tk.Label(main_frame, text="",
                                     bg="#f8f9fc", font=("Noto Sans JP", 11))
        self.status_label.pack()

        # ヒント
        tk.Label(main_frame, text="ヒント: ユーザー名「admin」パスワード「password123」",
                 bg="#f8f9fc", fg="#aaa", font=("Noto Sans JP", 9)).pack(pady=(8, 0))

    def toggle_pw(self):
        self.password_entry.config(show="" if self.show_pw.get() else "●")

    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get()

        if not username or not password:
            self.status_label.config(text="❗ ユーザー名とパスワードを入力してください", fg="#e67e22")
            return

        self.attempts += 1

        if username in self.USERS and self.USERS[username] == password:
            self.status_label.config(text=f"✅ ログイン成功!ようこそ、{username} さん!", fg="#27ae60")
            self.root.after(1500, self._show_welcome, username)
        else:
            remaining = self.max_attempts - self.attempts
            if remaining <= 0:
                self.status_label.config(text="🔒 試行回数オーバー。ロックされました", fg="#e74c3c")
                self.username_entry.config(state=tk.DISABLED)
                self.password_entry.config(state=tk.DISABLED)
            else:
                self.status_label.config(
                    text=f"❌ ユーザー名またはパスワードが違います(残り{remaining}回)", fg="#e74c3c")
            self.password_entry.delete(0, tk.END)

    def _show_welcome(self, username):
        for w in self.root.winfo_children():
            w.destroy()
        frame = tk.Frame(self.root, bg="#f8f9fc")
        frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
        tk.Label(frame, text="✅ ログイン成功",
                 font=("Noto Sans JP", 18, "bold"), bg="#f8f9fc", fg="#27ae60").pack(pady=(0, 12))
        tk.Label(frame, text=f"ようこそ、{username} さん!",
                 font=("Noto Sans JP", 14), bg="#f8f9fc").pack()
        ttk.Button(frame, text="ログアウト", command=self._logout).pack(pady=20)

    def _logout(self):
        for w in self.root.winfo_children():
            w.destroy()
        self.attempts = 0
        self._build_ui()


if __name__ == "__main__":
    root = tk.Tk()
    app = App33(root)
    root.mainloop()

LabelFrameによるセクション分け

ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。

import tkinter as tk
from tkinter import ttk, messagebox


class App33:
    """ログインフォーム"""

    # サンプルユーザー(実際のアプリではDBなどで管理)
    USERS = {
        "admin": "password123",
        "user1": "hello",
        "python": "guido",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("ログインフォーム")
        self.root.geometry("400x360")
        self.root.configure(bg="#f8f9fc")
        self.attempts = 0
        self.max_attempts = 3
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="ログインフォーム",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=40, pady=24)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # アイコン
        tk.Label(main_frame, text="🔐", font=("Segoe UI Emoji", 36),
                 bg="#f8f9fc").pack(pady=(0, 16))

        # フォーム
        form_frame = ttk.LabelFrame(main_frame, text="アカウント情報を入力", padding=14)
        form_frame.pack(fill=tk.X)

        tk.Label(form_frame, text="ユーザー名:").grid(row=0, column=0, sticky="w", pady=6)
        self.username_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12))
        self.username_entry.grid(row=0, column=1, padx=8, sticky="ew")

        tk.Label(form_frame, text="パスワード:").grid(row=1, column=0, sticky="w", pady=6)
        self.password_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12), show="●")
        self.password_entry.grid(row=1, column=1, padx=8, sticky="ew")
        self.password_entry.bind("<Return>", lambda e: self.login())

        # パスワード表示切替
        self.show_pw = tk.BooleanVar(value=False)
        ttk.Checkbutton(form_frame, text="パスワードを表示",
                        variable=self.show_pw,
                        command=self.toggle_pw).grid(row=2, column=1, sticky="w")
        form_frame.columnconfigure(1, weight=1)

        # ログインボタン
        tk.Button(main_frame, text="ログイン",
                  font=("Noto Sans JP", 13, "bold"),
                  bg="#3776ab", fg="white", activebackground="#2a5a8a",
                  relief=tk.FLAT, padx=20, pady=8,
                  command=self.login).pack(pady=14)

        self.status_label = tk.Label(main_frame, text="",
                                     bg="#f8f9fc", font=("Noto Sans JP", 11))
        self.status_label.pack()

        # ヒント
        tk.Label(main_frame, text="ヒント: ユーザー名「admin」パスワード「password123」",
                 bg="#f8f9fc", fg="#aaa", font=("Noto Sans JP", 9)).pack(pady=(8, 0))

    def toggle_pw(self):
        self.password_entry.config(show="" if self.show_pw.get() else "●")

    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get()

        if not username or not password:
            self.status_label.config(text="❗ ユーザー名とパスワードを入力してください", fg="#e67e22")
            return

        self.attempts += 1

        if username in self.USERS and self.USERS[username] == password:
            self.status_label.config(text=f"✅ ログイン成功!ようこそ、{username} さん!", fg="#27ae60")
            self.root.after(1500, self._show_welcome, username)
        else:
            remaining = self.max_attempts - self.attempts
            if remaining <= 0:
                self.status_label.config(text="🔒 試行回数オーバー。ロックされました", fg="#e74c3c")
                self.username_entry.config(state=tk.DISABLED)
                self.password_entry.config(state=tk.DISABLED)
            else:
                self.status_label.config(
                    text=f"❌ ユーザー名またはパスワードが違います(残り{remaining}回)", fg="#e74c3c")
            self.password_entry.delete(0, tk.END)

    def _show_welcome(self, username):
        for w in self.root.winfo_children():
            w.destroy()
        frame = tk.Frame(self.root, bg="#f8f9fc")
        frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
        tk.Label(frame, text="✅ ログイン成功",
                 font=("Noto Sans JP", 18, "bold"), bg="#f8f9fc", fg="#27ae60").pack(pady=(0, 12))
        tk.Label(frame, text=f"ようこそ、{username} さん!",
                 font=("Noto Sans JP", 14), bg="#f8f9fc").pack()
        ttk.Button(frame, text="ログアウト", command=self._logout).pack(pady=20)

    def _logout(self):
        for w in self.root.winfo_children():
            w.destroy()
        self.attempts = 0
        self._build_ui()


if __name__ == "__main__":
    root = tk.Tk()
    app = App33(root)
    root.mainloop()

Entryウィジェットとイベントバインド

ttk.Entryで入力フィールドを作成します。bind('', ...)でEnterキー押下時に処理を実行できます。これにより、マウスを使わずキーボードだけで操作できるUXが実現できます。

import tkinter as tk
from tkinter import ttk, messagebox


class App33:
    """ログインフォーム"""

    # サンプルユーザー(実際のアプリではDBなどで管理)
    USERS = {
        "admin": "password123",
        "user1": "hello",
        "python": "guido",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("ログインフォーム")
        self.root.geometry("400x360")
        self.root.configure(bg="#f8f9fc")
        self.attempts = 0
        self.max_attempts = 3
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="ログインフォーム",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=40, pady=24)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # アイコン
        tk.Label(main_frame, text="🔐", font=("Segoe UI Emoji", 36),
                 bg="#f8f9fc").pack(pady=(0, 16))

        # フォーム
        form_frame = ttk.LabelFrame(main_frame, text="アカウント情報を入力", padding=14)
        form_frame.pack(fill=tk.X)

        tk.Label(form_frame, text="ユーザー名:").grid(row=0, column=0, sticky="w", pady=6)
        self.username_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12))
        self.username_entry.grid(row=0, column=1, padx=8, sticky="ew")

        tk.Label(form_frame, text="パスワード:").grid(row=1, column=0, sticky="w", pady=6)
        self.password_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12), show="●")
        self.password_entry.grid(row=1, column=1, padx=8, sticky="ew")
        self.password_entry.bind("<Return>", lambda e: self.login())

        # パスワード表示切替
        self.show_pw = tk.BooleanVar(value=False)
        ttk.Checkbutton(form_frame, text="パスワードを表示",
                        variable=self.show_pw,
                        command=self.toggle_pw).grid(row=2, column=1, sticky="w")
        form_frame.columnconfigure(1, weight=1)

        # ログインボタン
        tk.Button(main_frame, text="ログイン",
                  font=("Noto Sans JP", 13, "bold"),
                  bg="#3776ab", fg="white", activebackground="#2a5a8a",
                  relief=tk.FLAT, padx=20, pady=8,
                  command=self.login).pack(pady=14)

        self.status_label = tk.Label(main_frame, text="",
                                     bg="#f8f9fc", font=("Noto Sans JP", 11))
        self.status_label.pack()

        # ヒント
        tk.Label(main_frame, text="ヒント: ユーザー名「admin」パスワード「password123」",
                 bg="#f8f9fc", fg="#aaa", font=("Noto Sans JP", 9)).pack(pady=(8, 0))

    def toggle_pw(self):
        self.password_entry.config(show="" if self.show_pw.get() else "●")

    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get()

        if not username or not password:
            self.status_label.config(text="❗ ユーザー名とパスワードを入力してください", fg="#e67e22")
            return

        self.attempts += 1

        if username in self.USERS and self.USERS[username] == password:
            self.status_label.config(text=f"✅ ログイン成功!ようこそ、{username} さん!", fg="#27ae60")
            self.root.after(1500, self._show_welcome, username)
        else:
            remaining = self.max_attempts - self.attempts
            if remaining <= 0:
                self.status_label.config(text="🔒 試行回数オーバー。ロックされました", fg="#e74c3c")
                self.username_entry.config(state=tk.DISABLED)
                self.password_entry.config(state=tk.DISABLED)
            else:
                self.status_label.config(
                    text=f"❌ ユーザー名またはパスワードが違います(残り{remaining}回)", fg="#e74c3c")
            self.password_entry.delete(0, tk.END)

    def _show_welcome(self, username):
        for w in self.root.winfo_children():
            w.destroy()
        frame = tk.Frame(self.root, bg="#f8f9fc")
        frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
        tk.Label(frame, text="✅ ログイン成功",
                 font=("Noto Sans JP", 18, "bold"), bg="#f8f9fc", fg="#27ae60").pack(pady=(0, 12))
        tk.Label(frame, text=f"ようこそ、{username} さん!",
                 font=("Noto Sans JP", 14), bg="#f8f9fc").pack()
        ttk.Button(frame, text="ログアウト", command=self._logout).pack(pady=20)

    def _logout(self):
        for w in self.root.winfo_children():
            w.destroy()
        self.attempts = 0
        self._build_ui()


if __name__ == "__main__":
    root = tk.Tk()
    app = App33(root)
    root.mainloop()

Textウィジェットでの結果表示

結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。

import tkinter as tk
from tkinter import ttk, messagebox


class App33:
    """ログインフォーム"""

    # サンプルユーザー(実際のアプリではDBなどで管理)
    USERS = {
        "admin": "password123",
        "user1": "hello",
        "python": "guido",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("ログインフォーム")
        self.root.geometry("400x360")
        self.root.configure(bg="#f8f9fc")
        self.attempts = 0
        self.max_attempts = 3
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="ログインフォーム",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=40, pady=24)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # アイコン
        tk.Label(main_frame, text="🔐", font=("Segoe UI Emoji", 36),
                 bg="#f8f9fc").pack(pady=(0, 16))

        # フォーム
        form_frame = ttk.LabelFrame(main_frame, text="アカウント情報を入力", padding=14)
        form_frame.pack(fill=tk.X)

        tk.Label(form_frame, text="ユーザー名:").grid(row=0, column=0, sticky="w", pady=6)
        self.username_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12))
        self.username_entry.grid(row=0, column=1, padx=8, sticky="ew")

        tk.Label(form_frame, text="パスワード:").grid(row=1, column=0, sticky="w", pady=6)
        self.password_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12), show="●")
        self.password_entry.grid(row=1, column=1, padx=8, sticky="ew")
        self.password_entry.bind("<Return>", lambda e: self.login())

        # パスワード表示切替
        self.show_pw = tk.BooleanVar(value=False)
        ttk.Checkbutton(form_frame, text="パスワードを表示",
                        variable=self.show_pw,
                        command=self.toggle_pw).grid(row=2, column=1, sticky="w")
        form_frame.columnconfigure(1, weight=1)

        # ログインボタン
        tk.Button(main_frame, text="ログイン",
                  font=("Noto Sans JP", 13, "bold"),
                  bg="#3776ab", fg="white", activebackground="#2a5a8a",
                  relief=tk.FLAT, padx=20, pady=8,
                  command=self.login).pack(pady=14)

        self.status_label = tk.Label(main_frame, text="",
                                     bg="#f8f9fc", font=("Noto Sans JP", 11))
        self.status_label.pack()

        # ヒント
        tk.Label(main_frame, text="ヒント: ユーザー名「admin」パスワード「password123」",
                 bg="#f8f9fc", fg="#aaa", font=("Noto Sans JP", 9)).pack(pady=(8, 0))

    def toggle_pw(self):
        self.password_entry.config(show="" if self.show_pw.get() else "●")

    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get()

        if not username or not password:
            self.status_label.config(text="❗ ユーザー名とパスワードを入力してください", fg="#e67e22")
            return

        self.attempts += 1

        if username in self.USERS and self.USERS[username] == password:
            self.status_label.config(text=f"✅ ログイン成功!ようこそ、{username} さん!", fg="#27ae60")
            self.root.after(1500, self._show_welcome, username)
        else:
            remaining = self.max_attempts - self.attempts
            if remaining <= 0:
                self.status_label.config(text="🔒 試行回数オーバー。ロックされました", fg="#e74c3c")
                self.username_entry.config(state=tk.DISABLED)
                self.password_entry.config(state=tk.DISABLED)
            else:
                self.status_label.config(
                    text=f"❌ ユーザー名またはパスワードが違います(残り{remaining}回)", fg="#e74c3c")
            self.password_entry.delete(0, tk.END)

    def _show_welcome(self, username):
        for w in self.root.winfo_children():
            w.destroy()
        frame = tk.Frame(self.root, bg="#f8f9fc")
        frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
        tk.Label(frame, text="✅ ログイン成功",
                 font=("Noto Sans JP", 18, "bold"), bg="#f8f9fc", fg="#27ae60").pack(pady=(0, 12))
        tk.Label(frame, text=f"ようこそ、{username} さん!",
                 font=("Noto Sans JP", 14), bg="#f8f9fc").pack()
        ttk.Button(frame, text="ログアウト", command=self._logout).pack(pady=20)

    def _logout(self):
        for w in self.root.winfo_children():
            w.destroy()
        self.attempts = 0
        self._build_ui()


if __name__ == "__main__":
    root = tk.Tk()
    app = App33(root)
    root.mainloop()

例外処理とmessagebox

try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。

import tkinter as tk
from tkinter import ttk, messagebox


class App33:
    """ログインフォーム"""

    # サンプルユーザー(実際のアプリではDBなどで管理)
    USERS = {
        "admin": "password123",
        "user1": "hello",
        "python": "guido",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("ログインフォーム")
        self.root.geometry("400x360")
        self.root.configure(bg="#f8f9fc")
        self.attempts = 0
        self.max_attempts = 3
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="ログインフォーム",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        main_frame = tk.Frame(self.root, bg="#f8f9fc", padx=40, pady=24)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # アイコン
        tk.Label(main_frame, text="🔐", font=("Segoe UI Emoji", 36),
                 bg="#f8f9fc").pack(pady=(0, 16))

        # フォーム
        form_frame = ttk.LabelFrame(main_frame, text="アカウント情報を入力", padding=14)
        form_frame.pack(fill=tk.X)

        tk.Label(form_frame, text="ユーザー名:").grid(row=0, column=0, sticky="w", pady=6)
        self.username_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12))
        self.username_entry.grid(row=0, column=1, padx=8, sticky="ew")

        tk.Label(form_frame, text="パスワード:").grid(row=1, column=0, sticky="w", pady=6)
        self.password_entry = ttk.Entry(form_frame, width=20, font=("Arial", 12), show="●")
        self.password_entry.grid(row=1, column=1, padx=8, sticky="ew")
        self.password_entry.bind("<Return>", lambda e: self.login())

        # パスワード表示切替
        self.show_pw = tk.BooleanVar(value=False)
        ttk.Checkbutton(form_frame, text="パスワードを表示",
                        variable=self.show_pw,
                        command=self.toggle_pw).grid(row=2, column=1, sticky="w")
        form_frame.columnconfigure(1, weight=1)

        # ログインボタン
        tk.Button(main_frame, text="ログイン",
                  font=("Noto Sans JP", 13, "bold"),
                  bg="#3776ab", fg="white", activebackground="#2a5a8a",
                  relief=tk.FLAT, padx=20, pady=8,
                  command=self.login).pack(pady=14)

        self.status_label = tk.Label(main_frame, text="",
                                     bg="#f8f9fc", font=("Noto Sans JP", 11))
        self.status_label.pack()

        # ヒント
        tk.Label(main_frame, text="ヒント: ユーザー名「admin」パスワード「password123」",
                 bg="#f8f9fc", fg="#aaa", font=("Noto Sans JP", 9)).pack(pady=(8, 0))

    def toggle_pw(self):
        self.password_entry.config(show="" if self.show_pw.get() else "●")

    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get()

        if not username or not password:
            self.status_label.config(text="❗ ユーザー名とパスワードを入力してください", fg="#e67e22")
            return

        self.attempts += 1

        if username in self.USERS and self.USERS[username] == password:
            self.status_label.config(text=f"✅ ログイン成功!ようこそ、{username} さん!", fg="#27ae60")
            self.root.after(1500, self._show_welcome, username)
        else:
            remaining = self.max_attempts - self.attempts
            if remaining <= 0:
                self.status_label.config(text="🔒 試行回数オーバー。ロックされました", fg="#e74c3c")
                self.username_entry.config(state=tk.DISABLED)
                self.password_entry.config(state=tk.DISABLED)
            else:
                self.status_label.config(
                    text=f"❌ ユーザー名またはパスワードが違います(残り{remaining}回)", fg="#e74c3c")
            self.password_entry.delete(0, tk.END)

    def _show_welcome(self, username):
        for w in self.root.winfo_children():
            w.destroy()
        frame = tk.Frame(self.root, bg="#f8f9fc")
        frame.pack(fill=tk.BOTH, expand=True, padx=40, pady=40)
        tk.Label(frame, text="✅ ログイン成功",
                 font=("Noto Sans JP", 18, "bold"), bg="#f8f9fc", fg="#27ae60").pack(pady=(0, 12))
        tk.Label(frame, text=f"ようこそ、{username} さん!",
                 font=("Noto Sans JP", 14), bg="#f8f9fc").pack()
        ttk.Button(frame, text="ログアウト", command=self._logout).pack(pady=20)

    def _logout(self):
        for w in self.root.winfo_children():
            w.destroy()
        self.attempts = 0
        self._build_ui()


if __name__ == "__main__":
    root = tk.Tk()
    app = App33(root)
    root.mainloop()

6. ステップバイステップガイド

このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。

  1. 1
    ファイルを作成する

    新しいファイルを作成して app33.py と保存します。

  2. 2
    クラスの骨格を作る

    App33クラスを定義し、__init__とmainloop()の最小構成を作ります。

  3. 3
    タイトルバーを作る

    Frameを使ってカラーバー付きのタイトルエリアを作ります。

  4. 4
    入力フォームを実装する

    LabelFrameとEntryウィジェットで入力エリアを作ります。

  5. 5
    処理ロジックを実装する

    _calculate()メソッドに計算・処理ロジックを実装します。

  6. 6
    結果表示を実装する

    TextウィジェットかLabelに結果を表示する_show_result()を実装します。

  7. 7
    エラー処理を追加する

    try-exceptとmessageboxでエラーハンドリングを追加します。

7. カスタマイズアイデア

基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。少しずつ機能を追加することで、Pythonのスキルが飛躍的に向上します。

💡 ダークモードを追加する

bg色・fg色を辞書で管理し、ボタン1つでダークモード・ライトモードを切り替えられるようにしましょう。

💡 データのエクスポート機能

計算結果をCSV・TXTファイルに保存するエクスポート機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。

💡 入力履歴機能

以前の入力値を覚えておいてComboboxのドロップダウンで再選択できる履歴機能を追加しましょう。

8. よくある問題と解決法

❌ 日本語フォントが表示されない

原因:システムに日本語フォントが見つからない場合があります。

解決法:font引数を省略するかシステムに合ったフォントを指定してください。

❌ ウィンドウのサイズが変更できない

原因:resizable(False, False)が設定されています。

解決法:resizable(True, True)に変更してください。

9. 練習問題

アプリの理解を深めるための練習問題です。難易度順に挑戦してみてください。

  1. 課題1:機能拡張

    ログインフォームに新しい機能を1つ追加してみましょう。どんな機能があると便利か考えてから実装してください。

  2. 課題2:UIの改善

    色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしてみましょう。

  3. 課題3:保存機能の追加

    入力値や計算結果をファイルに保存する機能を追加しましょう。jsonやcsvモジュールを使います。

🚀
次に挑戦するアプリ

このアプリをマスターしたら、次のNo.34に挑戦しましょう。