我会尝试类似这样的代码片段:
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
变量的人,它使代码可重用于其他目录和扩展,而无需创建新函数。