2014-02-08 81 views
0

請幫助修復腳本。如何在循環中綁定事件?

import tkinter 

root = tkinter.Tk() 
root.mainloop 

slides = { 
    'blue': 'active', 
    'red': 'active', 
    'green': 'unctive', 
    'orange': 'active', 
    'navy': 'active' 
} 


for (i, color) in enumerate(slides.keys()): 
    item = tkinter.Button(root, 
        text=color, 
        width=20, 
        height=10, 
        relief='raised', 
        borderwidth=5, 
        bg=color 
       ) 
    item.bind('<Button-1>', lambda event: invertItem(i, color)) 
    item.pack(side='left') 

def invertItem(i, color): 
    print(i, color) 

我需要點擊按鈕後顯示數字和名稱的顏色。現在,由於某種原因,總是顯示 「4個藍色」

回答

2
import tkinter 

root = tkinter.Tk() 

slides = { 
    'blue': 'active', 
    'red': 'active', 
    'green': 'unctive', 
    'orange': 'active', 
    'navy': 'active' 
} 

for (i, color) in enumerate(slides.keys()): 
    item = tkinter.Button(root, 
        text=color, 
        width=20, 
        height=10, 
        relief='raised', 
        borderwidth=5, 
        bg=color 
       ) 
    item.config(command=lambda i=i, color=color: invertItem(i, color)) 
    item.pack(side='left') 

def invertItem(i, color): 
    print(i, color) 

root.mainloop() 

變化:設置小部件後

  • 呼叫root.mainloop()。使用command選項代替bind
    • 添加默認參數i,color。否則,他們引用for循環的最後i,color
+0

但是鼠標點擊在哪裏? :) – Sergey

+0

@ user3218592,單擊按鈕時調用給'command'選項的回調函數。 – falsetru

相關問題