パーソナルブログメモリ

a = [1, 1]
for _ in "*" * 999: a += [sum(a[-2:])]
print(a)

treeコマンドで作成したリストから画像を表示するツールをtkinterで作ってみた

2020-08-20 | Python

完成品

 

tree コマンド

Ubuntu 18.04だとtreeコマンドは標準でないのでインストール

tree -f > tree.txt

実行したフォルダ配下の全ファイルをtree構造で表示する。

-f は実行フォルダ以下をフルパスで取得する。

 

初号機

作成したテキストファイルを読み込んで

ツリーの枝と画像ファイル以外のものを削除

 

二号機

viewerにしてみたくなり。tkinterにしてみます。

アプリケーション化しているクラスは参考文献のサンプルにcanvasを追加した程度のものです。

ともかくイメージをしっかり保持しておかないと、移して終わったと思うと表示の際に消えていたり、

タイマーで動かそうとしても、最後以外表示されなかったりいろいろと沼にはまりました。

ガベージコレクターがドンドン片付けるようなので表示されなかったらそれが原因かもしれません。

 

 

参考文献
tkinter — Python interface to Tcl/Tk

 

開発環境

Ubuntu 18.04.4 LTS

Python 3.7.5

 

ソースリスト

 

# $ tree -f > tree.txt で作成したファイル名から画像のものを表示するツールを作る
import tkinter as tk
from PIL import Image, ImageTk

def get_image_check(i):
    i=i.replace("\n","").lower()
    for j in [".jpg", ".png", ".jpeg"]:
        pos = i.find(j)
        if pos>-1 and pos+len(j)==len(i):return True
    return False

def get_pathfile_name(i):
    pos=i.find(".")
    return i[pos:].replace("\n", "")

class Application(tk.Frame):
    def __init__(self, master = None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()
    def create_widgets(self):
        global wx, wy
        self.b_next = tk.Button(self)
        self.b_next["text"] = "next\n(click me)"
        self.b_next["command"] = self.image_next
        self.b_next.pack(side="top")
        self.b_quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy)
        self.b_quit.pack(side="bottom")
        self.canvas = tk.Canvas(width = wx, height = wy-100)
        self.canvas.place(x=0, y = 100)
    def image_next(self):
        global wx, wy, imgs
        imgs = []
        for x in range(0, wx, 200):
            for y in range(0, wy-100 ,200):
                imgs += [image_chenge()]
                self.canvas.create_image(x, y, image = imgs[-1], anchor=tk.NW)

def image_chenge():
    global image_num
    image_num += 1
    if image_num > len(pathfile_list):image_num = 0
    img = Image.open(pathfile_list[image_num])
    print(pathfile_list[image_num])
    x, y = img.size
    rx,ry = 200, y/x*200
    if x/200 < y/200:
        rx, ry = x/y*200, 200
    return ImageTk.PhotoImage(img.resize((int(rx), int(ry)), Image.LANCZOS))

with open("./tree.txt") as f:
    tree_list = f.readlines()

pathfile_list = [get_pathfile_name(i) for i in tree_list if i != "\n" and get_image_check(i)]

image_num = 0
wx, wy = 1200, 900 #window_size
imgs = [] #ここにないと表示されるまでの間にガベージコレクトされるらしい

root = tk.Tk()
app = Application(master=root)
app.master.title("tree view Application")
app.master.minsize(wx, wy)
app.master.maxsize(wx, wy)
app.mainloop()


最新の画像もっと見る

コメントを投稿

ブログ作成者から承認されるまでコメントは反映されません。