python - 图像未显示在 Tkinter 中的标签上

标签 python image tkinter label

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

它们都在一个名为“cards”的文件夹中。 我正在运行 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()    

忽略额外的代码行,因为当我在程序上进行更多构建时,这些代码行将适用于该程序。这只是开始。

谢谢。

最佳答案

一个常见的错误,函数退出后,img 就会被垃圾回收,因此图像一旦放置在标签上就会消失。恕我直言,如果您要进行 GUI 编程,您应该学习类(class)。不管怎样,为了让它持久化,你可以附加到一个全局类实例,比如card1(显然我们没有图像,所以无法测试这个代码)。

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

关于python - 图像未显示在 Tkinter 中的标签上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751606/

相关文章:

html - 响应图像问题

javascript - 使用 css :hover to display an image on top of another one 时意外的闪烁效果

Python - 将包含 tkinter 小部件的框架传递到类中

python - 关于为什么我的 Django 表单不会呈现小部件类有什么想法吗?

python - 按长度和最后 N 个字符对字符串列表进行排序

python - 正则表达式搜索返回结果或为空

image - 使用opencv识别png格式图像的质量

Python 可嵌入 zip : install Tkinter

python - 如何在 tkinter 中自动包装小部件?

python - 在 Python 中使用模糊匹配合并多列数据帧