2012-10-18 30 views
2

我写一个程序有很多按钮(100),并且每一个都需要一个唯一的结果,但所有的结果都差不多,这是第一个按钮的代码创建众多独特的事件

box1= 'filepath to text file' 
def openfile(filename): 
    filetxt = (open(filename,"r").read()) 
    return filetxt 
    var.set(filetxt) 

def Box1(): 
    var.set(openfile(box1)) 

openfile(box1) 
window1 = Tk() 
window1.geometry('450x450') 

var = StringVar() 

Button1 = Button(donut,text = "Box #1", command= Box1) 
Button1.pack() 

每个按钮都会做同样的事情,但访问一个不同的文件,是否有更有效的方法来做到这一点,而不是简单地为每个按钮编写一个唯一的回调函数?

回答

2

通常情况下,你必须在列表中的文件:

list_of_files = ... 

然后,你将创建一个功能,使这将打开一个文件输入的按钮:

def file_open_button(filename): 
    b = Button(donut, text = 'open {0}'.format(filename), command = lambda: openfile(filename)) 
    return b 

现在遍历您文件列表并创建按钮,随时随地打包:

for f in list_of_files: 
    button = file_open_button(f) 
    button.pack() 

也许你错过的东西是一个下划线(匿名)功能的定位。 λ函数非常像常规函数:

def foo(x): 
    return x*x 

bar = lambda x: x*x 

上述语句非常相似。例如foo(x) == bar(x)将永远是True

+0

非常感谢!你是对的,我不明白lambda感谢解释 –

2

所有的按钮都可以共享一个回调。您可以使用lambda将文件名传递给回调。例如:

path="/path/to/the/file" 
b = Button(..., command=lambda f=path: openfile(f)) 

另一种选择是使用functools.partial。有人认为这比lambda更具可读性:

b = Button(..., command=functools.partial(openfile, path)) 
+0

Lambda应该工作,但我会去与functools.partial()。 – user1277476