LoginSignup
1
1

Python<Tkinter>備忘録【アプリ化】~ブクマ機能付きメモ帳作成編~

Posted at

はじめに

Pythonで作成したプログラムを実行ファイルに変換する手順です。

実行環境

  • Windows 10
  • Visual Studio
  • Python 3.11.3

以下のページを参考にしました。
Pythonファイルをexe/app化する。
python テキストエディタ作成 -tkinter-
【Python3】メッセージボックスの表示

プログラムを作成

お好きなプログラムを作成しましょう。
以下は、Tkinterを利用したサンプルです。

サンプルコード
import tkinter as tk
import tkinter.filedialog
from tkinter import messagebox
from time import sleep
import webbrowser

note = tk.Tk()
note.title('Hello, world.')

def file_load():
    abc = [('Text','*.txt'), ('Python','*.py')]
    fn = tk.filedialog.askopenfilename(filetypes=abc)
    if fn != '':
        f = None
        try:
            f = open(fn, 'r', encoding='utf-8')
            te.delete('1.0', 'end')
            te.insert('1.0', f.read())
        except:
            f = open(fn, 'r', encoding='shift-jis')
            te.delete('1.0', 'end')
            te.insert('1.0', f.read())
        finally:
            if f != None:
                f.close()

def file_save():
    abc = [("Text", "*.txt")]
    fn = tk.filedialog.asksaveasfilename(filetypes=abc)
    if fn != "":
        if fn[-4:] != ".txt":
            fn = fn + ".txt"
        with open(fn, 'w', encoding="utf-8") as f:
            f.write(te.get("1.0","end-1c"))

def close_app():
    if messagebox.askokcancel('-', 'アプリケーションを終了しますか?'):
        note.destroy()

menu_bar = tk.Menu()
menu0 = tk.Menu(menu_bar, tearoff=0)
menu0.add_command(label='ファイルを開く', command=file_load)
menu0.add_command(label='保存する', command=file_save)
menu0.add_separator()
menu0.add_command(label='終了', command=close_app)
menu_bar.add_cascade(label='ファイル', menu=menu0)
note['menu'] = menu_bar

pre = tk.Label(note, text='fish & chips')
pre.pack()
fr = tk.Frame()
fr.pack()
te = tk.Text(fr, width=80, height=30)
sc = tk.Scrollbar(fr, orient=tk.VERTICAL, command=te.yview)
sc.pack(side=tk.RIGHT, fill=tk.Y)
te.pack()
te[ 'yscrollcommand' ] = sc.set

def donut(btn1):
    sleep(0.5)
    webbrowser.open('https://www.google.com/')

def scone(btn2):
    sleep(0.5)
    webbrowser.open('https://qiita.com/')

btn1 = tk.Button(text='google', width=80)
btn1.pack()
btn1.bind('<Button-1>', donut)

btn2 = tk.Button(text='qiita', width=80)
btn2.pack()
btn2.bind('<Button-1>', scone)

note.mainloop()

コマンドプロンプトを起動

まずはpyinstallerを準備します。
(エラーが出た場合、pipのバージョンが古い可能性があります。)

pip3 install pyinstaller

次に、ファイルがある場所へ移動します。

cd desktop

Pythonのファイル名を指定して、以下を実行。

pyinstaller xxx.py --onefile --noconsole

ファイルと同じ場所に、distとbuildのふたつのフォルダが作成されます。
distフォルダ内にアプリケーションソフトが作成されていたら成功です!
お疲れさまでした。

おわり

お役に立てたら幸いです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1