1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

tkinter で表示した画像の切り替えをする

Last updated at Posted at 2019-09-13

#概要
tkinter で画像を表示させ,ボタンによってその切り替えを行う.

#環境

  • ubuntu 18.04 LTS
  • python 2.7

#問題
ボタンを押して画像が切り替わるプログラムを書いても,画像が消え黒いキャンバスだけが残る.

#解決方法

  • imgをグローバル変数として宣言する.
  • コールバック関数の中でもimgをグローバル変数として宣言する.

#プログラム例
以下のプログラムはimgをグローバル変数として宣言する箇所を抜粋し,キャンバスを描く等その他のプログラムは省略されている.

change_img
# -*- coding: utf-8-*-


import Tkinter as tk
from PIL import Image, ImageTk
import os
import time

global img #imgをグローバル変数とする


def btn1_click():
    print("スタート")


def btn2_click():
    global img #imgをグローバル変数とする
    print("リセット")

    path = ''
    img = Image.open(path)
    img = ImageTk.PhotoImage(img)

    canvas.create_image(0, 0, image=img, anchor=tk.NW, tag='photo')


def btn3_click():
    global img #imgをグローバル変数とする
    print("撮影")

    path = ''
    img = Image.open(path)
    img = ImageTk.PhotoImage(img)

    # キャンバスに画像を表示する。第一引数と第二引数は、x, yの座標
    canvas.create_image(0, 0, image=img, anchor=tk.NW, tag='photo')


def btn4_click():
    print("シャットダウン")

#実行例
Peek 2019-09-14 00-50.gif

#参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?