Skip to content

Instantly share code, notes, and snippets.

@curious-eyes
Created January 13, 2019 01:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curious-eyes/488d0413b57070e386a88f17778a064a to your computer and use it in GitHub Desktop.
Save curious-eyes/488d0413b57070e386a88f17778a064a to your computer and use it in GitHub Desktop.
Tkinter: 画像キャンバス更新にはGlobal変数が必要
"""
Tkinter サンプル
"""
import tkinter
from datetime import datetime
from PIL import ImageTk
def get_imagename():
""" ファイル名生成 """
seq = datetime.now().second % 2 + 1
filename = 'cat{:02d}.jpg'.format(seq)
print('image: {}'.format(filename))
return filename
#
# GUI設定
#
TKROOT = tkinter.Tk()
TKROOT.title(u"TkinterのCanvasを使ってみる")
TKROOT.geometry("805x805") #ウインドウサイズ(「幅x高さ」で指定)
#キャンバスエリア
ROOT_CANVAS = tkinter.Canvas(TKROOT, width=800, height=800)
# 画像表示してみる
IMG_DATA = ImageTk.PhotoImage(file=get_imagename())
IMG_CANVAS = ROOT_CANVAS.create_image(0, 0, image=IMG_DATA, anchor=tkinter.NW, tag="cats")
#キャンバスバインド
ROOT_CANVAS.place(x=0, y=0)
# 「描く」ボタン
def draw(event):
""" Click Event
"""
global IMG_DATA # <- グローバル参照を利用する
IMG_DATA = ImageTk.PhotoImage(file=get_imagename())
event.widget.itemconfig("cats", image=IMG_DATA, anchor=tkinter.NW)
ROOT_CANVAS.bind('<1>', draw)
# button_draw = tkinter.Button(TKROOT, text='update', width=15)
# button_draw.bind("<Button-1>", draw)
# button_draw.place(x=100, y=500)
#
# GUIの末端
#
TKROOT.mainloop()
@curious-eyes
Copy link
Author

同ディレクトリに cat01.png , cat02.png を配置する必要があります

@curious-eyes
Copy link
Author

$ pip install Pillow
も必要

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment