【发布时间】:2020-04-06 09:06:21
【问题描述】:
我正在尝试制作名为 Llama or 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()中创建的新标签下推。该图像未显示,因为它是在函数内部创建的并且已被垃圾回收。 -
@acw1668 我该如何解决?
标签: python python-3.x tkinter python-imaging-library