Reputation: 761
I am creating a GUI program that has 25 buttons, each accesses a unique file in the same folder, I know I can individually program each one to go to each file, but that seems like a lot more code than there needs to be, is there a more efficient way to do this? here is the code:
box1 = 'C:/Users/Geekman2/Documents/Tests/box1.txt
cupcake = Button(donut,text = "Box #1", command = open(box1))
done this way I would have to create a variable for every file,not very efficient
P.S. if you are confused, I name all of my variables after pastries
Upvotes: 1
Views: 148
Reputation: 889
I would try a code snippet similar to this:
directory = 'C:/Users/Geekman2/Documents/Tests/'
...
def AddDirTo(filename)
return directory + filename
Then the code you posted would turn into:
box1 = AddDirTo('box1.txt') #note: you did close box1's quote on your question
cupcake = Button(donut,text = "Box #1", command = open(box1))
If every file you have is a text file, as is indicated from the question's tays, you can even make it:
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))
For those of you about to vote this down for the directory
and extension
variables at the top, it makes the code reusable for other directories and extensions, without having to make a new function.
Upvotes: 1