LoginSignup
2
1

More than 3 years have passed since last update.

tkinterを使う

Last updated at Posted at 2019-08-04

pythonでtkinter使う。
tkinterは癖があるので、手間取ったときに書き足していく記事。

画像表示の関数化ができない

# 見本
# labelもしくはcanvas widgetのどちらか好きなほうで。
import tkinter as tk
import pyautogui
from PIL import ImageTk
root = tk.Tk()
img = pyautogui.screenshot(region = (12,34,56,78))
img = ImageTk.PhotoImage(img)
label = tk.Label(image=img)
label.pack()
root.mainloop()
# 関数化できない
import tkinter as tk
import pyautogui
from PIL import ImageTk

root = tk.Tk()
def test():
    img = pyautogui.screenshot(region = (12,34,56,78))
    img = ImageTk.PhotoImage(img)
    label = tk.Label(image=img)
    label.image = img # keep a reference!
    label.pack()
test()
root.mainloop()

pythonのガベージコレクションという機能でimg変数が破棄されている可能性があるとのこと。img.image = imgのようにimgインスタンス・オブジェクトの中にimageアトリビュートなどを作ってがっちりと保持する必要がある。
実行中のタイムライン全体にわたって存在する変数(グローバル変数的なもの)を作る必要がある。
PhotoImageで作ったものは破棄されるとの情報(stackoverflow)あり。

# 解決
# 行1を追加
import tkinter as tk
import pyautogui
from PIL import ImageTk

root = tk.Tk()
def test():
    img = pyautogui.screenshot(region = (12,34,56,78))
    img = ImageTk.PhotoImage(img)
    img.image = img #1
    label = tk.Label(image=img)
    label.pack()
test()
root.mainloop()

(参考文献)tkinterで画像が表示できない?

画像関係のエラーメッセージ

TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=●●x●● at 0x00000000>" doesn't exist
canvas object.canvas_image(0, 0, image = ここ)

画像の指定がうまくいっていない

続く

2
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
2
1