
田中太郎
今回は、メモ帳にメニューバーを追加します。
前回
前回はメモ帳に保存機能を搭載しました。
今回は、メニューバーを作成しましょう。
完成イメージ

メモ帳にメニューバーを追加します。
コード
notepad.py
import tkinter as tk
import notepad_func
root = tk.Tk()
# メニューバーを作成する
notepad_func.create_menubar(root)
# テキストボックスを作成する
text_widget = tk.Text(root, wrap=tk.CHAR)
text_widget.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.E, tk.W))
# テキストボックスの大きさを可変にする
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
# ctrl-sでファイルを保存
root.bind('<Control-KeyPress-s>', notepad_func.save_file_as)
# タイトルとかを設定
root.title("Notepad")
root.geometry("500x250")
root.mainloop()
notepad_func.py
import tkinter as tk
import tkinter.filedialog
def save_file_as(event=None):
"""名前を付けて保存する"""
f_type = [('Text', '*.txt')]
file_path = tkinter.filedialog.asksaveasfilename(
filetypes=f_type)
if file_path != "":
with open(file_path, "w") as f:
f.write(text_widget.get("1.0", "end-1c"))
return
def create_menubar(root):
"""メニューバーを作成する"""
menubar = tk.Menu(root)
# ファイル
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="新規(N)")
filemenu.add_command(label="開く(O)...")
filemenu.add_command(label="上書き保存(S)")
filemenu.add_command(label="名前を付けて保存(A)...", command=save_file_as)
filemenu.add_separator()
filemenu.add_command(label="終了(X)", command=root.destroy)
menubar.add_cascade(label="ファイル(F)", menu=filemenu)
# ヘルプ
helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="About...")
menubar.add_cascade(label="ヘルプ(H)", menu=helpmenu)
root.config(menu=menubar)
解説
create_menubar
メニューバーを作成します。
menubar = tk.Menu(root)
メニューバーのオブジェクトを作成します。
filemenu.add_command(label=”名前を付けて保存(A)…”, command=save_file_as)

メニューバーの内容を作成します。”名前を付けて保存(A)”をクリックするとcommand=save_file_asで指定した関数が起動します。
今回はファイル保存ダイアログが開きます。
filemenu.add_separator()
は上記の図の”名前を付けて保存(A)”と”終了(X)”の間の線を作っています。
まとめ
今回はメモ帳にメニューバーを追加しました。編集して、独自の機能を入れてみて下さい。