GUIコンポーネント・ウィジェット100本ノック1本目!

 import tkinter as tk

from tkinter import ttk


def show_knock():

    for child in container.winfo_children():

        child.destroy()

    

    name = combo.get()

    

    # --- 100本ノック メインロジック ---

    if name == "1. Label (浮き出し)":

        w = tk.Label(container, text="彫刻のようなラベル", relief="raised", bd=5, font=("Arial", 15))

    

    elif name == "2. Button (画像+文字)":

        # bitmapを使って、文字とアイコンを同時に表示

        w = tk.Button(container, text=" 保存", bitmap="info", compound="left", padx=10)

        

    elif name == "3. Entry (伏せ字)":

        w = tk.Entry(container, show="*", font=("Arial", 20)) # パスワード用

        

    elif name == "4. Text (色付き行)":

        w = tk.Text(container, width=20, height=3)

        w.insert("1.0", "ここは赤文字\n", "red_tag")

        w.tag_config("red_tag", foreground="red")

        w.insert("2.0", "ここは通常")

        

    elif name == "5. Checkbutton (トグル風)":

        w = tk.Checkbutton(container, text="スイッチ", indicatoron=False, selectcolor="green")

        

    elif name == "6. Radiobutton (複数行)":

        w = tk.Frame(container)

        v = tk.IntVar()

        for i in range(3):

            tk.Radiobutton(w, text=f"選択肢 {i+1}", variable=v, value=i, anchor="w").pack(fill="x")

            

    elif name == "7. Scale (垂直)":

        w = tk.Scale(container, from_=100, to=0, orient="vertical", label="温度")

        

    elif name == "8. Message (右寄せ)":

        w = tk.Message(container, text="右側に寄せて表示されるメッセージです。", width=150, justify="right")

        

    elif name == "9. Spinbox (リスト選択)":

        # 数字ではなく、特定の文字リストを回す

        w = tk.Spinbox(container, values=("晴れ", "曇り", "雨", "雪"), state="readonly")

        

    elif name == "10. Labelframe (中央タイトル)":

        w = tk.LabelFrame(container, text=" ログイン情報 ", labelanchor="n", padx=10, pady=10)

        tk.Entry(w).pack()


    w.pack(pady=20)

    container.update()


# --- ベース画面 ---

root = tk.Tk()

root.title("Tkinter 100本ノック 第1章")

root.geometry("400x500")


knock_list = [

    "1. Label (浮き出し)", "2. Button (画像+文字)", "3. Entry (伏せ字)",

    "4. Text (色付き行)", "5. Checkbutton (トグル風)", "6. Radiobutton (複数行)",

    "7. Scale (垂直)", "8. Message (右寄せ)", "9. Spinbox (リスト選択)",

    "10. Labelframe (中央タイトル)"

]


combo = ttk.Combobox(root, values=knock_list, state="readonly", width=25)

combo.set("ノックを選択してください")

combo.pack(pady=20)


tk.Button(root, text="ノック開始!", command=show_knock, bg="orange").pack()


container = tk.Frame(root, bd=2, relief="sunken", width=300, height=250)

container.pack(pady=20)

container.pack_propagate(False)


root.mainloop()


コメント

このブログの人気の投稿

ミライアイ内服薬は薬事法違反で、ほとんど効果がない詐欺ですか?

最高裁での上告理由書受理・却下の判断基準について

裁判官の忌避申立書の作成例