numpy Tkinter画布不更新照片

gcmastyq  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(123)

我正试图用tkinter制作一个照片编辑应用程序,它可以在按下按钮时对上传的图片执行一个动作(例如:翻转图片),但当按下按钮时,什么也不发生。操作图片的代码工作,我只是不能让屏幕上显示的变化。完整代码:

from PIL import Image, ImageTk
import PIL
import numpy as np
import tkinter as tk
from tkinter import *

image = PIL.Image.open('images.jpg')

img_data = np.array(image)

def button_flip_onClick():
    global canvas
    global image_container
    global img
    image_flipped_data = np.flip(img_data, axis=1)
    image_flipped = Image.fromarray(image_flipped_data)
    img = ImageTk.PhotoImage(image_flipped)
    image_container.config(canvas.create_image(10,10,anchor='nw',image=img))

SCREEN_WIDTH = 300
SCREEN_HEIGHT = 300

root = tk.Tk()

canvas = tk.Canvas(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
canvas.pack()
#Load an image in the script
img = ImageTk.PhotoImage(image)


image_container = canvas.create_image(10,10,anchor='nw',image=img)

button2 = tk.Button(root, text='flip', command= lambda:button_flip_onClick)
button2.place(relx=0.01, rely=0.7, relheight=0.15, relwidth=0.2)


root.mainloop()

我试过在函数中配置img,把image_container放在button2之后,在函数中配置画布。所有这些都导致了画面保持不变。

jtw3ybtb

jtw3ybtb1#

首先修改导入零件。

from PIL import Image, ImageTk
import numpy as np
import tkinter as tk

和,在button_flip_onClick函数中

image_container.config(canvas.create_image(10,10,anchor='nw',image=img))

将这一部分改为:

canvas.itemconfig(image_container, image=img)

当你的按钮调用一个函数时,你不需要lambda。即使你这样做,它也会起作用。

button2 = tk.Button(root, text='flip', command= button_flip_onClick)

完整的代码…

from PIL import Image, ImageTk
import numpy as np
import tkinter as tk

image = Image.open('images.jpg')

img_data = np.array(image)

def button_flip_onClick():
    global canvas
    global image_container
    global img
    image_flipped_data = np.flip(img_data, axis=1)
    image_flipped = Image.fromarray(image_flipped_data)
    img = ImageTk.PhotoImage(image_flipped)
    canvas.itemconfig(image_container, image=img)

SCREEN_WIDTH = 300
SCREEN_HEIGHT = 300

root = tk.Tk()

canvas = tk.Canvas(width=SCREEN_WIDTH, height=SCREEN_HEIGHT)
canvas.pack()
#Load an image in the script
img = ImageTk.PhotoImage(image)

image_container = canvas.create_image(10,10,anchor='nw',image=img)

button2 = tk.Button(root, text='flip', command= button_flip_onClick)
button2.place(relx=0.01, rely=0.7, relheight=0.15, relwidth=0.2)

root.mainloop()

我希望这会有所帮助。

相关问题