我正在创建一个具有 25 个按钮的 GUI 程序,每个按钮都访问同一文件夹中的一个唯一文件,我知道我可以单独对每个按钮进行编程以访问每个文件,但这似乎比需要的代码多得多有没有更有效的方法来做到这一点? 这是代码:
box1 = 'C:/Users/Geekman2/Documents/Tests/box1.txt
cupcake = Button(donut,text = "Box #1", command = open(box1))
这样做我必须为每个文件创建一个变量,效率不高
附注如果您感到困惑,我以糕点命名所有变量
最佳答案
我会尝试类似这样的代码片段:
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))
对于那些打算对顶部的directory
和extension
变量投反对票的人,它使代码可重用于其他目录和扩展,而无需创建一个新函数。
关于python - 从同一目录检索多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12922693/