【问题标题】:python image changing tkinter and PILpython图像更改tkinter和PIL
【发布时间】: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


【解决方案1】:

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

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

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()

【讨论】:

  • 谢谢!所以我可以理解global 用于识别def 之外的变量?
  • 是的,它告诉 Python 从全局空间中查找这些变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
相关资源
最近更新 更多