python:desktop_app
Tkinterを使ったデスクトップアプリの作成
基本パーツ
メインのウィンドウとラベル、1行のテキストエリア、ボタン等のテンプレート
import tkinter as tk root = tk.Tk() # メインウィンドウ作成 root.title("アプリのタイトル") # テキストエリアの作成 text_area_label = tk.Label(root, text="aaa") text_area_label.grid(row=0, column=0, sticky=tk.W) text_area = tk.Text(root, height=10) text_area.grid(row=1,column=0, columnspan=2, sticky=tk.W) def button_executed(): print("Executed") button = tk.Button(root, text="実行", width=10, command=button_executed) button.grid(row=0,column=1,sticky=tk.W) # メインループ root.mainloop()
コンテキストメニューを追加する
コンテキストメニューを追加するには、コンテキストメニューを追加させたいオブジェクトを指定して
tk.Menu(text_area, tearoff=0)
のように記載する。
tk.Menu
でメニューを作成し、add_command()
でメニューの項目を追加する。
tearoff=0
の設定はメニューを切り離せないようにするための設定。
do_popup()
を作成してを行う。text_area.bind(“<Button-3”, do_popup)
で、
テキストエリアの右クリックイベントにdo_popup()関数を結びつける。
event.x_root
とevent.y_root
によって、イベント発生時のマウスカーソルの座標を取得することができる。
import tkinter as tk from tkinter import filedialog import tkinter.messagebox as mb root = tk.Tk() # メインウィンドウ作成 root.title("アプリのタイトル") # テキストエリアの作成 text_area_label = tk.Label(root, text="aaa") text_area_label.pack() text_area = tk.Text(root) text_area.pack() # コンテキストメニューの作成 menu = tk.Menu(text_area, tearoff=0) def copy_selected(): # 選択範囲を取得 start, end = text_area.tag_ranges(tk.SEL) selected_text = text_area.get(start, end) # クリップボードにコピー root.clipboard_clear() root.clipboard_append(selected_text) menu.add_command(label="選択範囲をコピー", command=copy_selected) menu.add_command(label="すべてコピー", command=lambda: text_area.event_generate("<<Copy>>")) menu.add_command(label="貼り付け", command=lambda: text_area.event_generate("<<Paste>>")) menu.add_separator() menu.add_command(label="終了", command=root.quit) def do_popup(event): menu.tk_popup(event.x_root, event.y_root) text_area.bind("<Button-3>", do_popup) # メインループ root.mainloop()
python/desktop_app.txt · 最終更新: 2025/01/01 12:57 by mikoto