2013-05-03 86 views
0

這是我的第一個Python程序,我認爲我有if語句正確,我可能會也可能不會,我不知道。我想要做的是,當單擊一個Tkinter按鈕時,我想要調用的函數檢查哪個圖像正在顯示在按鈕上,然後相應地更改其圖像。帶有If語句的Tkinter按鈕

這裏是我的功能代碼:

def update_binary_text(first,second): 
    if buttonList[first][second]["image"] == photo: 
     buttonList[first][second]["image"] = photo1 

這裏的for循環[按鈕的2D列表]使用命令:

for i in range (0,number): 
     buttonList.append([]) 
     for j in range(0,number): 
      print(i,j) 
      buttonList[i].append(Button(game, borderwidth=0,highlightthickness=0, image=photo,command = lambda i=i, j=j: update_binary_text(i,j))) 
      buttonList[i][j].grid(row=i*20,column=j*20) 

問題是,當我運行它,它會打開很好,但是當我點擊所有的按鈕時,沒有任何反應。如果我拿出if語句並且只是放置作業,它會起作用,但我需要檢查首先顯示哪個圖像。
有沒有人有解決方案?


我剛碰到另一個問題。我之前收到的解決方案工作得很好,並且更改了圖像,但只在第一次點擊。之後,它不會再改變。

下面是代碼:

def update_binary_text(first,second): 
     #print("Called") 
     if buttonList[first][second].image == photo: 
       buttonList[first][second]["image"] = photo0 
     elif buttonList[first][second].image == photo0: 
       buttonList[first][second]["image"] = photo1 

發生的事情是,當我點擊任何按鈕,第一次,它將從一個空白按鈕變爲按鈕,上面有一個圖像,當我點擊它它應該改變它的形象,但它不會。如果有人想看看這裏的語句來初始化photophoto0photo1

photo = PhotoImage(file ="blank.gif") 
photo0 = PhotoImage(file="0.gif") 
photo1 = PhotoImage(file="1.gif") 

回答

1

我不知道什麼是photo的類型,但如果你把它作爲按鈕的選項,它不可能是一個串。問題是buttonList[first][second]["image"]返回一個字符串,而不是在構造函數中使用它的對象。

一個快速的解決辦法是增加一個_photo參考每個按鈕組件,然後用它在if語句photo比較:

def update_binary_text(first,second): 
    if buttonList[first][second]._photo == photo: 
     buttonList[first][second]["image"] = photo1 

# ... 

def create_button(i, j): 
    button = Button(game, borderwidth=0, highlightthickness=0, image=photo, 
        command = lambda i=i, j=j: update_binary_text(i,j)) 
    button._photo = photo 
    return button 

buttonList = [[create_button(i, j) for j in range(number)] for i in range(number)] 
+0

謝謝主席先生!我用._photo試了一下,沒有運氣,我嘗試了button.image,最後工作。謝謝! – vap 2013-05-04 21:59:58

+0

@vap是的,那是因爲你也需要實現其他方式(if語句,如果'.photo == photo1','image'選項設置爲'photo')。 – 2013-05-04 22:38:53

+0

哦!現在我明白了這是爲什麼。再次感謝! – vap 2013-05-04 23:06:33