【问题标题】:Image not showing on a label in Tkinter图像未显示在 Tkinter 的标签上
【发布时间】:2013-12-23 21:43:33
【问题描述】:

您好,我正在编写一个程序,向用户和计算机发送 26 张卡片。到目前为止,我只有一个按钮来显示位于用户牌组顶部的卡片。 我有一个标签,我有一个卡片图像文件夹,其名称以花色的首字母 H、S、C、D 命名,卡片名称为 2、3、4...、10、J、Q、K,一个。例如,红桃 5 是 H5.bmp。它们都是 .bmp 文件。该程序与卡片图像位于同一文件夹中。

它们都在一个名为卡片的文件夹中。 我正在运行 python 2.5 和 Tkinter 作为 GUI 构建器。

from random import choice
from Tkinter import *
suits=['H','S','C','D']
cards=['2','3','4','5','6','7','8','9','10','J','Q','K','A']
user=[]
comp=[]
used=[]
userturn=True

def deal():
    global user,comp,used
    numcards=1
    while numcards<=26:
        current=(choice(suits),choice(cards))
        while current in used:
            current=(choice(suits),choice(cards))
        user.append(current)
        used.append(current)
        numcards+=1
    for suit in suits:
        for card in cards:
            if (suit,card) not in user:
                comp.append((suit,card))
def place():
    if userturn and len(user)>0:
        current=user[0]
        print current
        del user[0]
        img='%s%s.bmp'%(current[0],current[1])
        card1.config(image=img)


master=Tk()
card1=Label(master,text='')
card1.pack()
card2=Label(master,text='')
card2.pack()
card3=Label(master,text='')
card3.pack()
card4=Label(master,text='')
card4.pack()
card5=Label(master,text='')
card5.pack()
play=Button(master,text='Play',command=place)
play.pack()
deal()
master.mainloop()    

忽略额外的代码行,因为随着我更多地构建程序,这些代码行将应用于程序。这只是一个开始。

谢谢。

【问题讨论】:

  • 您在place 命令中设置按钮小部件的图像,这是按下按钮时的回调。这是一种相当复杂的处理方式:您正在配置按钮在绘制后应该如何显示,并且只有在用户单击它之前。这可能是它不起作用的原因。这个问题可能更适合codereview.stackexchange.com,如果没有其他问题,人们可以帮助您改进代码的样式。
  • 不,我正在更新标签的图像而不是按钮。
  • 你是对的,我看错了对不起。

标签: python image tkinter label


【解决方案1】:

一个常见的错误,img 函数一退出就会被垃圾回收,所以图像一放在标签上就会消失。如果您要编写 GUI,您应该学习课程恕我直言。无论如何,要使其持久化,您可以附加到全局类实例,例如 card1(显然我们没有图像,因此无法测试此代码)。

    img_name='%s%s.bmp'%(current[0],current[1])
    img=BitmapImage(file=img_name)
    card1.img = img
    card1.config(image=card1.img)

【讨论】:

  • 其实问题是有一个TCL错误说图片不存在。我什至尝试添加完整的路径名。
  • 这是正确答案,它解决了问题中的两个问题:(1)image 参数必须是 PhotoImage 或 BitmapImage 对象,而不是 str,以及(2)必须保留对图像的引用以避免它被垃圾收集。注意:实际上应该在这个答案中使用 PhotoImage 而不是 BitmapImage 。而且 PhotoImage 只接受 GIF 和 PGM/PPM 文件,所以无论是图片还是代码都需要稍作修改。
【解决方案2】:

你的代码有两个问题:

  1. place() 中,您忘记指定保存图像的文件夹的路径img='%s%s.bmp'%(current[0],current[1])仅指定图像的名称,而不指定它们所在文件夹的路径。因此,您收到了错误消息:TCL 错误说图像不存在。

  2. 一旦你修复了我上面所说的,你仍然必须通过运行card1.image = img 来在place() 方法中保留对图像的引用

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多