Created
January 13, 2019 01:33
-
-
Save curious-eyes/488d0413b57070e386a88f17778a064a to your computer and use it in GitHub Desktop.
Tkinter: 画像キャンバス更新にはGlobal変数が必要
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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() |
$ pip install Pillow
も必要
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
同ディレクトリに cat01.png , cat02.png を配置する必要があります