前提
tkinterで画像を表示するアプリを作成しました。
「open」ボタンでファイルダイアログを起動し、画像を選択して表示します。
このアプリに、ボタンを押すと同じフォルダ内の次の画像(または前の画像)に切り替えられる機能を付加したいです。
※IrfanViewというアプリでは「←」「→」といったボタンで画像を遷移できますが,あれと同じようなイメージです。
実現したいこと
アプリの
「next」ボタンを押す→次の画像を表示
「back」ボタンを押す→前の画像を表示
といった機能を実現したい。
図のようなフォルダ内の画像を順に表示したい。
該当のソースコード
Python 3.7.4
example.py
1import tkinter as tk 2from tkinter import filedialog 3from tkinter import ttk 4 5 6def push_load_button(): 7 file_path = tk.filedialog.askopenfilename(initialdir=".") 8 global before_image 9 10 if len(file_path) != 0: 11 # 画像オブジェクトの作成 12 before_image = tk.PhotoImage(file=file_path) 13 14 # 画像の位置を調節 15 x = int(canvas_width / 2) 16 y = int(canvas_height / 2) 17 18 # キャンバスに描画中の画像を削除 19 if canvas_obj is not None: 20 canvas.delete(canvas_obj) 21 22 # 画像をキャンバスに表示 23 before_canvas_obj = canvas.create_image(x, y, image=before_image) 24 25 26root = tk.Tk() 27root.geometry("1000x1000") 28root.title("画像表示アプリ") 29frame = ttk.Frame(root, padding=5) 30frame.pack(padx=5, pady=5) 31 32canvas_width = 850 33canvas_height = 640 34canvas = tk.Canvas(root, width=canvas_width, height=canvas_height, bg="gray") 35canvas.pack(pady=10, ipadx=10) 36 37# ボタンを設置するフレームの作成 38button_frame = tk.Frame() 39button_frame.pack(pady=10, ipadx=10) 40 41# 画像オブジェクトの設定(初期はNone) 42before_image = None 43 44# キャンパスに描画中の画像(初期はNone) 45canvas_obj = None 46 47# ファイル読み込みボタンの作成と配置 48load_button = tk.Button(button_frame, text="open", command=push_load_button) 49load_button.pack(pady=10, ipadx=10) 50 51# 次の画像へ遷移するボタンの作成と配置 52button1 = tk.Button(button_frame, text="next") 53button1.pack(pady=20, ipadx=18) 54 55# 前の画像へ遷移するボタンの作成と配置 56button2 = tk.Button(button_frame, text="back") 57button2.pack(pady=5, ipadx=18) 58 59 60root.mainloop()
試したこと
Qiitaなどで調べましたが、「同じフォルダ内の画像を自分の意思で切り替え」といった内容を見つけられませんでした。
まだ勉強し始めたばかりの初心者で煩雑な部分もあり申し訳ないですが、実装するためのコードや使えそうな関数などだけでも教えていただけるとありがたいです。
補足情報(FW/ツールのバージョンなど)
・tkinter 8.6
回答1件
あなたの回答
tips
プレビュー