1

我正在创建一个有 25 个按钮的 GUI 程序,每个按钮访问同一个文件夹中的一个唯一文件,我知道我可以单独编程每个按钮以访问每个文件,但这似乎比需要的代码多得多,是有更有效的方法吗?这是代码:

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

这样做我将不得不为每个文件创建一个变量,效率不高

PS如果你感到困惑,我用糕点命名我的所有变量

4

1 回答 1

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变量的人,它使代码可重用于其他目录和扩展,而无需创建新函数。

于 2012-10-16T20:40:40.317 回答