The thing is, I'm creating a window. This is the code for one of the buttons:
self.btn51 = tkinter.Button(master, text="0", command = self.printBut0)
self.btn51.place(x=180, y=380, width=120, height=40)
self.btn51.configure(font=("Caviar_Dreams", "15"))
What they do is: when I press the button it prints the digit "0" in an Entry. And this is the function that is called by the button:
def printBut0(self):
self.txtCalc.insert(len(self.txtCalc.get()),"0")
The thing is that I repeat the function many times because there are several buttons with that function, but they print different digits, can I somehow make one for all the buttons?
And I appreciate if you can tell me something that I can improve.
To avoid duplicating code you have to identify what is changing. In this case, to create a button, vary the
text
,x
ey
. Then we put that data into a list of dictionaries:Since
printBut0
it depends ontext
the button's, we adapt it so that it receives it as an argument by keyword :Then, you can use a for loop to iterate through the list and create the buttons:
We use the function
partial
of the modulefunctools
so that the methodprintBut
receives thattext
of the corresponding button. What it does is return the same method but with an argument already applied. An example of its use: