首页 > 解决方案 > python图像更改tkinter和PIL

问题描述

我正在尝试制作名为 Llama 或 Duck 的游戏,但使用的是猫和立方体。我的问题是当我单击立方体时,按钮消失并且图像不会改变。

这是我的代码:

from tkinter import *
import random
from PIL import Image, ImageTk
window=Tk()
window.geometry('500x550')
window.resizable(False, False)
f=tk.Frame()
f.config(bg='blue', height='500', width='500')
f.pack()
def imageelection():
    images=['cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'cube1.jpg', 'cube2.jpg', 'cube3.jpg']
    imageselection=ImageTk.PhotoImage(file=random.choice(images))
    img = Label(f, image=imageselection)
    img.pack()
images=['cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'cube1.jpg', 'cube2.jpg', 'cube3.jpg']
rand=random.choice(images)
imageselection=ImageTk.PhotoImage(file=rand)
img = Label(f, image=imageselection)
img.pack()
def cubeelection():
    if rand=='cube1.jpg':
        imageelection()
    elif rand=='cube2.jpg':
        imageelection()
    elif rand=='cube3.jpg':
        imageelection()
    else:
        print('fail')
        imageelection()
cat=tk.Button(window, text='Cat')
cat.config()
cat.pack(fill=X)
cube=tk.Button(window, text='Cube', command=cubeelection)
cube.config()
cube.pack(fill=X)
window.mainloop()

标签: pythonpython-3.xtkinterpython-imaging-library

解决方案


按钮被在中创建的新标签按下(超出可视区域)imageelection()。内部创建的图像imageelection()是本地的,在函数完成后将被垃圾收集。

据我了解,您不需要在里面创建新标签imageelection(),只需更新img标签。为了在函数内部更改后保留图像,您需要将imageselection和声明rand为全局变量:

images=['cat1.jpg', 'cat2.jpg', 'cat3.jpg', 'cube1.jpg', 'cube2.jpg', 'cube3.jpg']

def imageelection():
    global imageselection, rand
    rand = random.choice(images) # select another image
    imageselection = ImageTk.PhotoImage(file=rand)
    img.config(image=imageselection)

rand = random.choice(images)
imageselection = ImageTk.PhotoImage(file=rand)
img = Label(f, image=imageselection)
img.pack()

def cubeelection():
    if rand in ['cube1.jpg', 'cube2.jpg', 'cube3.jpg']:
        print('ok')
    else:
        print('fail')
    imageelection()

推荐阅读