2012-10-16 36 views
1

我正在创建一个具有25个按钮的GUI程序,每个程序访问同一个文件夹中的一个独特文件,我知道我可以单独编程每个文件去查看每个文件,但这似乎很多比需要的代码更多,是否有更高效的方法来执行此操作? 这里是代码:从同一目录中检索多个文件

box1 = 'C:/Users/Geekman2/Documents/Tests/box1.txt 
cupcake = Button(donut,text = "Box #1", command = open(box1)) 

做到这样,我就必须创建一个变量为每一个文件,不是很有效

附:如果你感到困惑,我的名字我的所有变量的糕点

+1

如果您分享了您想要帮助优化的代码,这将会很有帮助。 –

+0

编写一个python程序来编写一个将对所有文件路径进行硬编码的python程序。 – TheZ

+5

“如果你感到困惑,请将糕点后的所有变量都命名为” - 如果我是你,我会克服那种习惯*真实*快。 – I82Much

回答

1

我会尝试一段代码类似于此之后:

directory = 'C:/Users/Geekman2/Documents/Tests/' 
... 
def AddDirTo(filename) 
    return directory + filename 

然后你发布的代码就会变成:

box1 = AddDirTo('box1.txt') #note: you did close box1's quote on your question 
cupcake = Button(donut,text = "Box #1", command = open(box1)) 

如果您拥有的每个文件都是文本文件,如问题所示,您甚至可以创建它:

directory = 'C:/Users/Geekman2/Documents/Tests/' 
extension = '.txt' 
... 
def AddDirTo(filename): 
    return directory + filename + extension 
... 
box1 = AddDirTo('box1') #note: you did close box1's quote on your question 
cupcake = Button(donut,text = "Box #1", command = open(box1)) 

对于那些想要为顶部的directoryextension变量进行投票的代码,它使代码可以重复使用于其他目录和扩展,而不必创建新函数。

+0

非常感谢你,这正是我所需要的 –

相关问题