2011-08-21 52 views
5

我想將10個按鈕添加到Tkinter,名爲One to Ten。我基本上只使用暴力方法,在我的應用程序類的init函數中添加每個按鈕。它的工作原理,但我想盡量減少使用的代碼,更有效率,如使用數據結構來保存所有的按鈕。如何有效地將很多按鈕添加到tkinter框架?

我正在考慮用buttonBox來放置所有的按鈕,但我不確定我是否可以通過grid()來操作放置按鈕的方式。

self.one = Button(frame, text="One", command=self.callback) 
self.one.grid(sticky=W+E+N+S, padx=1, pady=1) 

self.two = Button(frame, text="Two", command=self.callback) 
self.two.grid(sticky=W+E+N+S, row=0, column=1, padx=1, pady=1) 

self.three = Button(frame, text="Three", command=self.callback) 
self.three.grid(sticky=W+E+N+S, row=0, column=2, padx=1, pady=1) 

# ... 

self.ten = Button(frame, text="Ten", command=self.callback) 
self.ten.grid(sticky=W+E+N+S, row=1, column=4, padx=1, pady=1) 

任何人都可以讓我看到一種更高效的方法,比如數據結構嗎?

回答

4

相反命名的按鈕self.oneself.two等,這將是更方便的通過索引列表,如self.button引用它們。

如果按鈕做不同的事情,那麼你就必須有回調明確 副按鈕。例如:

name_callbacks=(('One',self.callback_one), 
       ('Two',self.callback_two), 
       ..., 
       ('Ten',self.callback_ten)) 
self.button=[] 
for i,(name,callback) in enumerate(name_callbacks): 
    self.button.append(Button(frame, text=name, command=callback)) 
    row,col=divmod(i,5) 
    self.button[i].grid(sticky=W+E+N+S, row=row, column=col, padx=1, pady=1) 

如果按鍵都做類似的東西,然後一個回調可能足以爲他們服務所有。由於回調本身不能接受參數,你可以設置一個回調工廠通過閉合傳遞參數中:

def callback(self,i): # This is the callback factory. Calling it returns a function. 
    def _callback(): 
     print(i) # i tells you which button has been pressed. 
    return _callback 

def __init__(self): 
    names=('One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten') 
    self.button=[] 
    for i,name in enumerate(names): 
     self.button.append(Button(frame, text=name, command=self.callback(i+1))) 
     row,col=divmod(i,5) 
     self.button[i].grid(sticky=W+E+N+S, row=row, column=col, padx=1, pady=1) 
+1

謝謝!這工作,但我不得不將它更改爲「self.button.append()」,所以它不會導致IndexError。而底線我改爲self.button [i] .grid(),而不是self.one.grid()。它完美的工作:) – thatbennyguy

+0

@thatbennyguy:Ack!感謝您的更正! – unutbu

+0

只有一件事......你如何獲得按鈕來回調不同的命令? – thatbennyguy

1

你可以把所有的按鈕性質的字典,然後循環它來創建你的按鈕,這裏有一個例子:

buttons = { 
    'one': {'sticky': W+E+N+S, 'padx': 1, 'pady': 1}, 
    'two': {'sticky': W+E+N+S, 'row': 0, 'column': 1, 'padx': 1, 'pady': 1}, 
    'three': {'sticky': W+E+N+S, 'row': 0, 'column': 2, 'padx': 1, 'pady': 1} 
} 
for b in buttons: 
    button = Button(frame, text=b.title(), command=self.callback) 
    button.grid(**buttons[b]) 
    setattr(self, b, button) 

這也將使得在需要時您可以輕鬆地添加新的按鈕。