1

这似乎是一个非常简单的问题,但是单击按钮时我无法显示 jpg 图像。这是我的代码(由于时间原因没有按钮代码):

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

谢谢!

4

1 回答 1

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 中,PhotoImage 可以打开 GIF、PPM/PGM 图像。要打开其他格式,您可能需要安装 Pillow(Python3 的 PIL 项目的一个分支)。

于 2013-07-09T01:49:03.230 回答