嗨,我正在编写一个程序,向用户和计算机发 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/