2013-12-23 35 views
1

我正在寫一個程序,向用戶和計算機交易26張卡片。到目前爲止,我只有一個顯示位於用戶卡組頂部的卡片的按鈕。 我有一個標籤,我有一個卡片圖像的文件夾,名稱以西裝的首字母大寫,H,S,C,D和卡片2,3,4 ...,10,J,Q,K ,一個。例如,5顆心是H5.bmp。他們都是.bmp文件。該程序與卡片圖像位於同一個文件夾中。圖片沒有在Tkinter的標籤上顯示

他們都在一個名爲卡片的文件夾中。 我正在運行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()  

忽略額外的代碼行,因爲這些代碼會在我構建它時應用到程序中。這只是開始。

謝謝。

+0

你在'place'命令設置按鈕控件的形象,以保持內部place()方法您的圖片參考這是按鈕被按下時的回調。這是一種相當複雜的事情:您正在配置按鈕在已經被繪製之後應該如何顯示,並且直到用戶點擊它爲止。這可能是它不工作的原因。這個問題可能更適合http://codereview.stackexchange.com/,如果沒有其他人可以幫助你改善代碼的風格。 – Iguananaut

+0

不,我正在更新標籤的圖像而不是按鈕。 – user2658538

+0

你說得對,我誤解對不起。 – Iguananaut

回答

0

一個常見的錯誤,一旦函數退出,img就會被垃圾回收,所以圖像一放到標籤上就立即消失。如果你要編程圖形用戶界面,你應該學習類恕我直言。無論如何,爲了讓它持久,你可以附加到一個全局類實例,比如card1(顯然,我們沒有圖像,所以不能測試這個代碼)。

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

其實問題是有一個TCL錯誤說圖像不存在。我甚至嘗試添加完整的路徑名。 – user2658538

0

有兩個問題與您的代碼:

  1. 裏面place()你忘了指定到您的圖片保存文件夾的路徑。該行img='%s%s.bmp'%(current[0],current[1])僅指定圖像的名稱,但不指定文件夾的路徑。因此你得到了錯誤信息:TCL錯誤,說圖像不存在。

  2. 一旦固定了我上文所述,你仍然有運行card1.image = img