2013-07-09 2 views
1

Это похоже на довольно простой вопрос, но у меня проблемы с отображением jpg-изображения при нажатии кнопки. Вот мой код (без кода кнопки во времени):Отображение .jpg изображения при нажатии кнопки в Tkinter?

from tkinter import * 

#screen stuff here 

canvas = Canvas(app) 
canvas.grid(row = 0,column = 0) 
photo = PhotoImage(file = "test.jpg") 
canvas.create_image(0,0, image = photo) 


def show_image(): 
    global canvas 
    global photo 
    canvas.create_image(0,0, image = photo) 

#button that calls the function down here 

Спасибо!

ответ

1

Это работает с python2:

import Tkinter as tk 
import ImageTk 

def show_image(): 
    x = canvas.create_image(125, 125, image=tk_img) 
    while True: 
     print('show') 
     canvas.itemconfigure(x, state=tk.NORMAL) 
     button.configure(text = 'Hide') 
     yield 
     print('hide')   
     canvas.itemconfigure(x, state=tk.HIDDEN) 
     button.configure(text = 'Show')   
     yield 

root = tk.Tk() 
canvas = tk.Canvas(root, width=250, height=250) 
canvas.grid(row=0, column=0) 
tk_img = ImageTk.PhotoImage(file='image.png') 

button = tk.Button(
    root, text="Show", command=show_image().next, anchor='w', 
    width=10, activebackground="#33B5E5") 
button.grid(row=1, column=0) 
root.mainloop() 

В Python3, PhotoImagecan open GIF, PPM/PGM images. Чтобы открыть другие форматы, вы можете need to install Pillow (вилка проекта PIL для Python3).

+0

Я все еще получаю такую ​​же ошибку ... хммм. Есть ли другие способы показать изображение? – codeforfood

Смежные вопросы