could you tell me whether there is a more elegant solution to my code what I need?
My little program takes text input from up to seven entry fields (exact number can be specified by the user). The input strings are then concatenated with interspersed fixed text elements. A single output in the form of a string is generated.
The program works perfectly fine. Yet, my programming strikes me as very inelegant and non-pythonic. Could you help me to improve, to foster my learning?
Two points:
1) I like to sum up the string length of all seven text inputs. I plainly added them, which is not elegant. How could I do it a better way?
string_length = len(str(E1.get())) + len(str(E2.get())) + len(str(E3.get())) + len(str(E4.get())) + len(str(E5.get())) + len(str(E6.get())) + len(str(E7.get()))
2) Depending on the number of entry field which can be specified by the user using a Tkinter Scale S, Entry fields(En) are enabled or disabled for taking input.
The Strings str(En.get()) derived from these Entry field are then concatenated with the fixed string elements partM in between to give rise to the string m. (The whole string is flanked with partL and partR on each side also.) I have done this by query the variable of the scale S (number of entry fields) via the get() method. The program then decides how to proceed via if / elif?
The higher the scale is set the more text elements are added. Yet this is highly similar task which strikes me as there might be a more straight forward solution.
This creates long lines of code and is not very amenable for scaling up the program for taking more Entry fields. How could I do it better?
code excerpt:
if S.get() == 1:
if string_length == 22*S.get():
m = partL + str(E1.get()) + partR
do_something()
else:
warning()
elif S.get() == 2:
if string_length == 22*S.get():
m = partL + str(E1.get()) + partM + str(E2.get()) + partR
do_something()
else:
warning()
elif S.get() == 3:
if string_length == 22*S.get():
m = partL + str(E1.get()) + partM + str(E2.get()) + partM + str(E3.get()) + partR
do_something()
else:
warning()
I am very new to Python. I am also new to programming. Yet I am proud I write a little code that works fine and does something useful for me and others. I welcome any suggestions.