python - 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()
解决方案
按钮被在中创建的新标签按下(超出可视区域)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()
推荐阅读
- c# - 如何设置一个在 C# 中使用字符串?
- java - 如何使用我自己的属性、规范和可分页创建自定义 Spring Data JPA 查找方法?
- sql-server - SQL Server 全文搜索在时间窗口内的最大性能限制
- c# - AspNet 用户声明丢失
- google-apps-script - getActiveCell() 总是返回 1,1
- ansible - Ansible 测试变量以什么开头
- android - 在 Android 中将字符串作为文件附件共享
- swift - 如何告诉用户准确的度数是朝北还是朝东?
- scala - Cats - EitherT - 发散隐式扩展以进行理解而无需显式输入?
- javascript - E/configParser - ReferenceError: 元素未定义