2011-08-21 50 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) 

这也将使得在需要时您可以轻松地添加新的按钮。