I am writing a program with a lot of buttons(over 100), and each one needs a unique result, but all of the results are similar, this is the code of the first button
box1= 'filepath to text file'
def openfile(filename):
filetxt = (open(filename,"r").read())
return filetxt
var.set(filetxt)
def Box1():
var.set(openfile(box1))
openfile(box1)
window1 = Tk()
window1.geometry('450x450')
var = StringVar()
Button1 = Button(donut,text = "Box #1", command= Box1 )
Button1.pack()
each button will do the same thing, but access a different file, is there a more efficient way to do this than simply writing a unique callback function for every button?
Usually, you’d have the files in a list:
Then you would create a function to make a button which opens a file input:
Now iterate over your list of files and create the buttons, packing as you go:
Perhaps the thing you’re missing is an understanding of
lambda(anonymous) functions. a lambda function is much like a regular function:The above statements are very similar. e.g.
foo(x) == bar(x)will always beTrue.