2017-02-11 132 views
0

我想從列表創建按鈕併爲每個按鈕分配一個基於列表項的功能。我在下面嘗試,按鈕不響應點擊。我看到一個解決方案,其中使用lambda函數將參數傳遞給一個函數,但我希望單獨的函數。 Anaconda的使用Python 3.5Tkinter從列表創建按鈕,每個按鈕都有其自己的功能

import tkinter as tk 

def North(): 
    print('slected North') 

def South(): 
    print('slected South') 

def East(): 
    print('slected East') 

def West(): 
    print('slected West') 

lst = ['North','South','East','West'] 
win = tk.Tk() 
win.title = 'Compass' 
for col,Direction in enumerate(lst): 
     butName = tk.Button(win, text = Direction, command = Direction) 
     butName.grid(row = 1, column = col) 


win.mainloop() 

回答

0

你的列表中包含;它需要包含功能

lst = [North,South,East,West] 
0

更快,更好:

import tkinter as tk 

def onbutton_click(label): 
    print('selected ', label) 

lst = ['North','South','East','West'] 
win = tk.Tk() 
win.title = 'Compass' 
for col,Direction in enumerate(lst): 
    butName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e)) 
    butName.grid(row=0, column=col) 

win.mainloop() 

或用自己的方式:

import tkinter as tk 

def North(): 
    print('slected North') 

def South(): 
    print('slected South') 

def East(): 
    print('slected East') 

def West(): 
    print('slected West') 

lst = [North, South,East, West] 
win = tk.Tk() 
win.title = 'Compass' 
for col,Direction in enumerate(lst): 
    butName = tk.Button(win, text=Direction.__name__, command=Direction) 
    butName.grid(row=0, column=col) 

win.mainloop() 

我還設置了一排爲0的原因有沒有必要將1.