I would like through a list or dict populated by a text to create a frames, this way I could update an app without having to mess with the code, can someone help me?

Seria algo assim:

vars.txt:

tab1 <-> nome1
tab2 <-> nome2
tab3 <-> nome3
tab4 <-> nome4

tab5 <-> nome5

varlist = open("Confs/vars.txt", "r").readlines()
for line in varlist:
     tab, nome = line.split('<->')   
     tab = ttk.Frame(tabControl)
     tabControl.add(tab, text=nome)
     tabControl.pack(expand=1, fill="both")

 makesubmenu(nome,tab)

can this be done?
thanks

While there is no tab control widget built into TKInter, there are a number of ways to implement one, with the best option probably being to use a Notebook widget as the parent for a TabControl class.

this already bellongs to a notebbok

tabControl = ttk.Notebook(tabmain1)

im trying to do this also in order of not having 10 or more like this

 #tab1
  Tab1 = ttk.Frame(tabControl)
    tabControl.add(Tab1, text='Initialized messages')

    # Tab2
    tab2 = ttk.Frame(tabControl)
    tabControl.add(tab2, text='Change Configuration')
    tabControl.pack(expand=1, fill="both")

    # Tab3
    tab3 = ttk.Frame(tabControl)
    tabControl.add(tab3, text='Clear Cache')
    tabControl.pack(expand=1, fill="both")

    .....

    tab10
    ......

If a more compact format is the goal, It should be possible,and not especially difficult, to wrap the the tabmain1 in a class which takes a list or dictionary and destructures it into the above code. However, unless you are expecting to reuse this a lot - a good deal more than 10 entries in a single form - it may not be worth the effort.

I should add that, given the original problem, you probably could avoid the class implementation (which I've already tried before realizing this) by simply using the for: loop you already demonstrated earlier. Your original code ought to work with some modifications:

tabControl = ttk.Notebook(root)
varlist = open('Confs/vars.txt', 'r').readlines()
for line in varlist:
    title, data = line.split('<->')   
    tab = ttk.Frame(tabControl)
    tabControl.add(tab, text=title)
    ttk.Label(tab, text=data).grid(column=0, row=0, padx=10, pady=10)
tabControl.pack(expand=1, fill='both')

Note that you only need to pack the widget once, when it is fully populated.

I had misinterpreted the main question initially, which is why I went to down the rabbit hole of developing a class to wrap all of this in.

Schol-R-LEA, that wont work, all the tabs will be tab and not tab1, tab2, tab3....

and even when i tried i get

frmbtnspecs = ttk.Frame(Tab1)
frmbtnspecs.pack(side=TOP)

NameError: name 'tab1' is not defined

Would a list of tab objects be suitable? Given the tabN format. using a list instead seems an obvious improvement (since you would be able to iterate through the list if needed), unless I am missing something.

    tab = list()
    for i, line in enumerate(varlist):
        title, data = line.split('<->')   
        tab.append(ttk.Frame(tabControl))
        tabControl.add(tab[i], text=title)
        ttk.Label(tab[i], text=data).grid(column=0, row=0, padx=10, pady=10)
    tabControl.pack(expand=1, fill='both')
commented: this doesnt work still get error tab1 is missing +0

I dont know iif it helps any, but this is the class (and a brief test program) I had initially come up with when I misconstrued your question; you may find it useful despite it not matching your actual immediate needs.

import tkinter as tk                    
from tkinter import ttk

class TextTabControl (ttk.Notebook):
    def __init__(self, rootWidget, parentWidget, tabData):
        """A TextTabControl consists of a Notebook and 
        a dictionary of tab names and tab data.
        In the current version, this cannot be added to later,
        but it should be possible to extend the class later to 
        make it more flexible."""
        super().__init__(rootWidget)
        self.__root__ = rootWidget
        self.__tabData__ = tabData
        # populate the tabs
        for key in self.__tabData__:
            tab = parentWidget(self) 
            ttk.Label(tab, text=self.__tabData__[key]).grid(column=0, row=0, padx=10, pady=10)
            super().add(tab, text = key)
        # pack the final set of tab widgets   
        self.pack(expand = 1, fill ="both")


if __name__ == "__main__":
    root = tk.Tk()
    root.title("Tab Widget")
    textTabControl1 = TextTabControl(root, 
                                     ttk.Frame, 
                                     {"Welcome": "Welcome to the demo",
                                      "Tab 1": "tab data 1",
                                      "Tab 2": "tab data 2",
                                      "Tab 3": "tab data 3",
                                      "Tab 4": "tab data 4",
                                      "Tab 5": "tab data 5",
                                      "Tab 6": "tab data 6"})


    root.mainloop()  

Thanks :)

the class worked but im having some dificulty populating it right

here how i have it

varconfbook = open("Confs/json_dumps.txt", "r").readlines()
class TextTabControl(ttk.Notebook):
    def __init__(self, rootWidget, parentWidget, tabData):
        super().__init__(rootWidget)
        self.__root__ = rootWidget
        self.__tabData__ = tabData
        # populate the tabs
        for key in self.__tabData__:
            tab = parentWidget(self)
            ttk.Label(tab, text=self.__tabData__[key]).grid(column=0, row=0, padx=10, pady=10)
            super().add(tab, text=key)
        # pack the final set of tab widgets
        self.pack(expand=1, fill=&quot;both&quot;)




lsttiporeq1 = []# list with tab1, tab2 tab3, etc....
tabblers = []#list with names of tab 
for line in varconfbook:
    tabb, title, xxx1, xxx2, xxx3 = line.split('&lt;-&gt;')
    if tabb not in tabblers:
        tabblers.append(tabb)
    if title not in lsttiporeq1:
        lsttiporeq1.append(title)

for x in lsttiporeq1:             
    textTabControl1 = TextTabControl(tabmain1,
                                 ttk.Frame,
                                 {x})

maybe i should just do it like this

lsttiporeq1 = []
tabblers = []
for line in varconfbook:
    tabb, tiporeq, titreq, jsonreq, expectresq = line.split('<->')
    if tabb not in tabblers:
        tabblers.append(tabb)
    if tiporeq not in lsttiporeq1:
        lsttiporeq1.append(tiporeq)

if "tab1" in tabblers:
    # tab1
    tab1 = ttk.Frame(tabControl)
    tabControl.add(tab1, text=lsttiporeq1[x])

if "tab2" in tabblers:
# Tab2
    tab2 = ttk.Frame(tabControl)
    tabControl.add(tab2, text=lsttiporeq1[x])
    tabControl.pack(expand=1, fill="both")

and create 30tab in order to compensate for future updates

how do i get the correct x, im pretty sure im not doing this right :s

maybe

        for line in varconfbook:
    tabb, tiporeq, titreq, jsonreq, expectresq = line.split('<->')
    if "tab1" in tabb and tab1done:
        tab1 = ttk.Frame(tabControl)
        tabControl.add(tab1, text=tiporeq)
        tabControl.pack(expand=1, fill="both")
        tab1done=1

    if "tab2" in tabb and tab2done:
        tab2 = ttk.Frame(tabControl)
        tabControl.add(tab2, text=tiporeq)
        tabControl.pack(expand=1, fill="both")
        tab2done=1

this doesnt work still get error tab1 is missing

You would access it with tab[1] rather than tab1.

In my experience, most of the cases where you want to use var1, var2, ... varN, you are better off using an array or (in the case of Python) a list or dictionary.

Python lists are similar to arrays in many other languages, but are more flexible in that they are heterogeneous, that is to say, you can put different kinds of objects into them. Also, since they are linked lists rather than fixed arrays, you can add to them and remove things from them at very little cost.

Dictionaries are a bit more complex, being what in other languages is sometimes called a hash table or lookup table. They consist of a series of key/value pairs where the value can be found by using the key. As with lists, both the key and the value can be of almost any type, though the key has to be a value which can be compared uniquely to other possible keys.

Usually, with a class you would have the class in a separate file from the rest of the code, and import the class so you can use it. But that's up to you.

Right now, though, the way you are using it, you are creating several TextTabControl and assigning each to a local TextTabControl1, which I don't think would work as they would spanw several temporary TextTabControl objects and then overwrite them.

As for making a list of tabN names, well, that's sort of what a dictionary would be used for usually, but in this case, as I said earlier, it would make more sense to me to simply use a list of the tabs in the first place and access them as tab[]. If you really need to access them by their tab names, then a dictionary would be the way to go.

Maybe it would help if you showed us more of the code, so we could have more context for all of this. Do you have an offiste repo for you version control, where we could view the whole project? I highly recommend using version control for even the smallest of projects, and using an offsite repo such as GitHub or SourceForge to keep an online copy of it where it would be safer from crashes (though you still want to do local backups) and could easily be shared.

import time
from tkinter import *
import tkinter as tk
from tkinter import ttk, PhotoImage, LabelFrame, Text, GROOVE, Button, Label, scrolledtext
from tkinter.scrolledtext import ScrolledText
import requests
import json
from xpto.makeReport import savetoxls



###########################################nova janela####################################

def gera_forms(get_inp_cond_id, get_inp_cond_endpoint):
    from xpto.formularios import tabmain1, frmmain, btngera, getcondicion

    frmmain.pack_forget()
    btngera.pack_forget()
    getcondicion()


    nome_endpoint, timeoutvar, url_endpoint = get_inp_cond_endpoint.split('<:>')
    nome_endpoint = nome_endpoint.replace('  ', '').strip()
    url_endpoint = url_endpoint.replace(' ', '').strip()
    timeoutvar = timeoutvar.replace(' ', '').strip()


    photRun = PhotoImage(file=r'img/run.png')
    photoOK = PhotoImage(file=r'img/ok.png')
    photoNot = PhotoImage(file=r'img/notok.png')

    headers = {'Content-Type': 'application/json', 'chargeid':'TACW2242520G0479'}

    tiporeq = ""
    payload = json.dumps({})
    expResp = ""

    varconfbook = open("Confs/json_dumps.txt", "r").readlines()
    lsttiporeq = []
    lsttitreq = []
    lstjsonreq = []
    lstexpectresq = []





    def makesubmenu(tipo_de_conf, framename):
        cont = 0
        rowcont=0

        frm_json_case_button = ttk.Frame(framename)
        frm_json_case_button.grid(column=0, row=0, rowspan=99)

        frm_txt_json_case = ttk.Frame(framename)
        frm_txt_json_case.grid(column=1, row=0)



        url_show=ttk.Label(frm_txt_json_case, text=nome_endpoint + "  @  " + str(url_endpoint + tipo_de_conf) + "  @  " + get_inp_cond_id)
        url_show.grid(column=1, row=0, columnspan=99, padx=10, pady=10)

        ttk.Label(frm_txt_json_case, text="Request:").grid(column=2, row=1, padx=10, pady=10)
        reqst_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        reqst_input.grid(column=2, row=2, padx=10, pady=10, ipady=35)

        ttk.Label(frm_txt_json_case, text="Expected Response:").grid(column=2, row=3, rowspan=1, padx=10, pady=10)
        lblexpect = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        lblexpect.grid(column=2, row=4, padx=10, pady=10, ipady=15)



        resp_json_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        resp_json_input.grid(column=4, row=2, padx=10, pady=10, ipady=35)

        ttk.Button(frm_txt_json_case, text="Run", image=photRun,command=lambda resp_json=resp_json_input, reqtxt=reqst_input, tiporeq=tipo_de_conf: runpost(resp_json, reqtxt, tiporeq)).grid(column=3, row=2, padx=10, pady=10, ipady=65)
        ttk.Label(frm_txt_json_case, text="Response:").grid(column=4, row=1, padx=10, pady=10)

        ttk.Label(frm_txt_json_case, text="Response / OBS:").grid(column=3, row=3, columnspan=5, padx=10, pady=10)
        resp_kiblog = ScrolledText(frm_txt_json_case, width=95, height=10)
        resp_kiblog.grid(column=3, row=4, padx=10, columnspan=5, rowspan=10, pady=10, ipady=120)

        frm_but_oknot = ttk.Frame(frm_txt_json_case)
        frm_but_oknot.grid(column=2, row=5, padx=1, pady=1)

        ttk.Button(frm_but_oknot, width="15", text="OK", image=photoOK, command=lambda: savetoxls(jsonresponse)).grid(column=0, row=0,padx=1, pady=15)
        ttk.Button(frm_but_oknot, width="15", text="Not Ok", image=photoNot).grid(column=1, row=0, padx=1, pady=15)


        for line in varconfbook:
            if tipo_de_conf in line:
                tabbxx, tiporeq, titreq, jsonreq, expectresq = line.split('<->')
                lsttiporeq.append(tiporeq)
                lsttitreq.append(titreq)
                lstjsonreq.append(jsonreq)
                lstexpectresq.append(expectresq)

                ttk.Button(frm_json_case_button, width="20", text=titreq, command=lambda lblexp=lblexpect, reqtxt=reqst_input, cont=cont: ChangConfWI(int(cont),reqtxt,lblexp)).grid(column=0, row=rowcont, padx=10, pady=10)
                rowcont += 1

            cont += 1

        return lsttiporeq, lsttitreq, lstjsonreq, lstexpectresq, reqst_input, lblexpect, resp_json_input,resp_kiblog



    def ChangConfWI(tipreq,reqtxt,lblexp):
    #try:
        reqtxt.delete('1.0', END)
        lblexp.delete('1.0', END)
        reqtxt.insert(tk.INSERT, lstjsonreq[tipreq])
        lblexp.insert(tk.INSERT, str(lstexpectresq[tipreq]))
    #except Exception as e:
     #   from  xpto.main import log_error
      #  log_error(e, "ChangConfWI")>


    def runpost(resp_json,reqtxt,tiporeq):
        try:
            getconfval = reqtxt.get(1.0, "end-1c")
            if len(getconfval)>1:
                resp_json.delete('1.0', END)
                resp_json.insert(tk.INSERT, str(url_endpoint+tiporeq)+", headers="+str(headers)+", data=json.dumps("+str(getconfval)+"), timeout="+str(timeoutvar)+"\n\n\n")
                reqjson = requests.request("POST", str(url_endpoint+tiporeq), headers=headers, data=json.dumps(getconfval), timeout=int(timeoutvar))
                statReason = ("Request:\n\n" + getconfval + "\n\nStatus:\n\n" + str(reqjson.status_code) + " - " + str(reqjson.reason) + "\n\nResponse:\n\n" + str(reqjson.text))
                resp_json.insert(tk.INSERT, statReason)
                jsonresponse=resp_json.get(1.0, "end-1c")
        except Exception as e:
           from  xpto.main import log_error
           resp_json.insert(tk.INSERT, "\n\n"+str(e)+"\n\n")
           log_error(e, "runpost")









#######Gera tabuladores##################################
    tabControl = ttk.Notebook(tabmain1)
    ########################################################################################################
#i whantd to do this from a txt in order to add more tab´s without changing the code

    # tab1
    tab1 = ttk.Frame(tabControl)
    tabControl.add(tab1, text="first")


    # Tab2
    tab2 = ttk.Frame(tabControl)
    tabControl.add(tab2, text="GConfiguration")
    tabControl.pack(expand=1, fill="both")

    # Tab3
    tab3 = ttk.Frame(tabControl)
    tabControl.add(tab3, text='Cache')
    tabControl.pack(expand=1, fill="both")

    # Tab4
    tab4 = ttk.Frame(tabControl)
    tabControl.add(tab4, text='Get')
    tabControl.pack(expand=1, fill="both")

    # Tab5
    tab5 = ttk.Frame(tabControl)
    tabControl.add(tab5, text='something ')
    tabControl.pack(expand=1, fill="both")

    # Tab6
    tab6 = ttk.Frame(tabControl)
    tabControl.add(tab6, text='Get  List')
    tabControl.pack(expand=1, fill="both")

    # Tab7
    tab7 = ttk.Frame(tabControl)
    tabControl.add(tab7, text='Remote Start ')
    tabControl.pack(expand=1, fill="both")

    # Tab8
    tab8 = ttk.Frame(tabControl)
    tabControl.add(tab8, text='Remote Stop ')
    tabControl.pack(expand=1, fill="both")

    # Tab9
    tab9 = ttk.Frame(tabControl)
    tabControl.add(tab9, text='Reset')
    tabControl.pack(expand=1, fill="both")

    # tab10
    tab10 = ttk.Frame(tabControl)
    tabControl.add(tab10, text=' Local List')
    tabControl.pack(expand=1, fill="both")

    # tab11
    tab11 = ttk.Frame(tabControl)
    tabControl.add(tab11, text='Unlock ')
    tabControl.pack(expand=1, fill="both")

    # tab12
    tab12 = ttk.Frame(tabControl)
    tabControl.add(tab12, text='Update ')
    tabControl.pack(expand=1, fill="both")


    ############################################################################################################

 # i whantd to do this from a txt in order to add more tab´s without changing the code
    makesubmenu("first", tab1)

    makesubmenu("GConfiguration",tab2)

    makesubmenu("Cache",tab3)

    makesubmenu("Get",tab4)

    makesubmenu("something", tab5)

    ...



    #i have a txt that is set like this

tab1<->GetConfiguration<->opt1
tab1<->GetConfiguration<->opt2
tab1<->GetConfiguration<->opt3
tab2<->GetConfiguration<->opt1
tab3<->GetConfiguration<->opt1
tab3<->GetConfiguration<->opt2
tab4<->GetConfiguration<->opt1
tab4<->GetConfiguration<->opt2
tab5<->GetConfiguration<->opt1
tab6<->GetConfiguration<->opt1

hope this can help

Hmmn, unfortunately, I can't find a copy of the library xpto.makeReport you are using for writing the report forms to, so I can't test the program as a whole. However, as I said before, using a list should work instad of tabN. I would start by populating a list or a dictionary, either by reading from a file as you've been doing:

varlist = open("vars.txt", "r").readlines()
tabMenus = dict()
for line in varlist:        
    title, data = line.split('<->')
    tabMenus[title] = data

or simply by reserving a Python configuration file, Confs/tab.py which may actually be the easier option if it is acceptable:

tabMenus = {
    'first': 'text a', 
    'GConfiguration': 'text b', 
    'Cache': 'text c', 
    'Get': 'text d', 
    'something ': 'text e', 
    'Get List': 'text f',
    'Remote Start': 'text g', 
    'Remote Stop': 'text h', 
    'Local List': 'text i', 
    'Unlock': 'text j', 
    'Update': 'text k'
}

which you would import thusly:

import Confs.tabs

Either way, you would have a function which walks through the dictionary

def generateTabs(root, parent, tabMenus):
    tabControl = ttk.Notebook(root)
    tab = list()
    for i, key in enumerate(tabMenus.keys()):
        tab.append(parent(tabControl))
        tabControl.add(tab[i], text=key)
    tabControl.pack(expand=1, fill="both")    
    return tab

... which you would use as so:

tab = generateTabs(root, tabmain1, tabMenus)

for i, key in enumerate(tabMenus.keys()):
    makesubmenu(tabMenus[key], tab[i])

I hope this helps.

commented: Can you explain what root does? im not getting it :( tabmain1 the the root i guess, its tabControl = ttk.Notebook(tabmain1) +1

Can you explain what root does? im not getting it :( tabmain1 the the root i guess, its tabControl = ttk.Notebook(tabmain1)

Well, root is a commonly used name for the main window of a single-window application, which is what is returned by tkinter.Tk() (usually abbreviated to tk.Tk() by use of import renaming). Your own code does use it in this manner.

The parent , on the other hand, is the control which the new control is immediately a part of, in this case tabmain1 from the sounds of it.

I was assuming that the overall root would be needed by the function, but it looks as if parent (== tabmain1) might be the only value needed here.

I've had to work from some assumptions about how the actual code will work, since I can't see it running as things are. If you could provide a link to the xpto library so I could run the original code myself, and see exactly what it is suppose to do, that might help me help you.

i, thanks, im still testing it and its not ready yet, but if you like its this

from xlwt import XFStyle, Font, Workbook
import xlwt
import time

filename = "Reports/"+time.strftime("%Y%m%d-%H%M%S")+'_easlo1.xls'
wb = Workbook()
sheet1 = wb.add_sheet('Test')


global valColuna, valRow
valColuna = 0
valRow = 0

def savetoxls(jsonresponse):

    #  set the font
    style = xlwt.XFStyle()
    font = xlwt.Font()
    font.bold = True  # bold
    font.name = 'Times New Roman'  # select the font
    font.underline = False  # font underline
    font.italic = False  # italics
    font.height = 300  # the font size
    font.colour_index = 4  # the font color ::1-branco, 2-vermelho, 3-verde, 4-azul
    style.font = font

    style = xlwt.easyxf('pattern: pattern solid, fore_colour red')

    # VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
    aligment = xlwt.Alignment()
    aligment.horz = aligment.HORZ_JUSTIFIED  # horizontal alignment
    aligment.vert = aligment.VERT_JUSTIFIED  # perpendicular to its way
    style.alignment = aligment

    valColuna = +1
    valRow = +1

    sheet1.col(int(valColuna)).width = 13500  # MAX:65535
    sheet1.write(int(valRow), int(valColuna), str(jsonresponse), style)  # response
    wb.save(filename)

you can also just remove the import and jsonresponse=resp_json.get(1.0, "end-1c")

OK, that helps, though now I guess I would need an example of the input to gera_forms() in order to test the whole function. Sorry to keep hassling you about that, but I want to see what the function actually does in order to see if my advice has been what you need.

Again, this is a place where having an publicly accessible repo, on a site such as Github or Sourceforge, would help tremendously.

dont apologise, i apologise, your helping me thank you so much.

geraform us called by

 gera_forms(get_inp_cond_id, get_inp_cond_endpoint)

something like: gera_forms(stat1,nome_end<->30<->http://something.com)
get_inp_cond_endpoint=(nome_end<->30<->http://something.com)

you can run it like this

import os
import time
from tkinter import *
import tkinter as tk
from tkinter import ttk, PhotoImage, LabelFrame, Text, GROOVE, Button, Label, scrolledtext
from tkinter.scrolledtext import ScrolledText
import requests
import json


global get_inp_cond_endpoint, get_inp_cond_id
tabmain1 = Tk()
w, h = tabmain1.winfo_screenwidth(), tabmain1.winfo_screenheight()
tabmain1.geometry("%dx%d+0+0" % (w, h))


frmmain = Label(tabmain1, text='')
frmmain.pack(side='top', fill='x', expand=False)
###########################################nova janela####################################

def gera_forms(get_inp_cond_id, get_inp_cond_endpoint):


    frmmain.pack_forget()




    nome_endpoint, timeoutvar, url_endpoint = get_inp_cond_endpoint.split('<:>')
    nome_endpoint = nome_endpoint.replace('  ', '').strip()
    url_endpoint = url_endpoint.replace(' ', '').strip()
    timeoutvar = timeoutvar.replace(' ', '').strip()


    photRun = PhotoImage(file=r'/Users/ricardosimoes/PycharmProjects/pythonProject/OCP/img/run.png')
    photoOK = PhotoImage(file=r'/Users/ricardosimoes/PycharmProjects/pythonProject/OCP/img/ok.png')
    photoNot = PhotoImage(file=r'/Users/ricardosimoes/PycharmProjects/pythonProject/OCP/img/notok.png')

    headers = {'Content-Type': 'application/json', 'chargingstation':'stat1'}

    tiporeq = ""
    payload = json.dumps({})
    expResp = ""

    varconfbook = open("/Users/ricardosimoes/PycharmProjects/pythonProject/OCP/Confs/json_dumps.txt", "r").readlines()
    lsttiporeq = []
    lsttitreq = []
    lstjsonreq = []
    lstexpectresq = []





    def makesubmenu(tipo_de_conf, framename):
        cont = 0
        rowcont=0

        frm_json_case_button = ttk.Frame(framename)
        frm_json_case_button.grid(column=0, row=0, rowspan=99)

        frm_txt_json_case = ttk.Frame(framename)
        frm_txt_json_case.grid(column=1, row=0)



        url_show=ttk.Label(frm_txt_json_case, text=nome_endpoint + "  @  " + str(url_endpoint + tipo_de_conf) + "  @  " + get_inp_cond_id)
        url_show.grid(column=1, row=0, columnspan=99, padx=10, pady=10)

        ttk.Label(frm_txt_json_case, text="Request:").grid(column=2, row=1, padx=10, pady=10)
        reqst_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        reqst_input.grid(column=2, row=2, padx=10, pady=10, ipady=35)

        ttk.Label(frm_txt_json_case, text="Expected Response:").grid(column=2, row=3, rowspan=1, padx=10, pady=10)
        lblexpect = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        lblexpect.grid(column=2, row=4, padx=10, pady=10, ipady=15)



        resp_json_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        resp_json_input.grid(column=4, row=2, padx=10, pady=10, ipady=35)

        ttk.Button(frm_txt_json_case, text="Run", image=photRun,command=lambda resp_json=resp_json_input, reqtxt=reqst_input, tiporeq=tipo_de_conf: runpost(resp_json, reqtxt, tiporeq)).grid(column=3, row=2, padx=10, pady=10, ipady=65)
        ttk.Label(frm_txt_json_case, text="Response:").grid(column=4, row=1, padx=10, pady=10)

        ttk.Label(frm_txt_json_case, text="Response / OBS:").grid(column=3, row=3, columnspan=5, padx=10, pady=10)
        resp_kiblog = ScrolledText(frm_txt_json_case, width=95, height=10)
        resp_kiblog.grid(column=3, row=4, padx=10, columnspan=5, rowspan=10, pady=10, ipady=120)

        frm_but_oknot = ttk.Frame(frm_txt_json_case)
        frm_but_oknot.grid(column=2, row=5, padx=1, pady=1)

        ttk.Button(frm_but_oknot, width="15", text="OK", image=photoOK, command=lambda: savetoxls(jsonresponse)).grid(column=0, row=0,padx=1, pady=15)
        ttk.Button(frm_but_oknot, width="15", text="Not Ok", image=photoNot).grid(column=1, row=0, padx=1, pady=15)


        for line in varconfbook:
            if tipo_de_conf in line:
                tabbxx, tiporeq, titreq, jsonreq, expectresq = line.split('<->')
                lsttiporeq.append(tiporeq)
                lsttitreq.append(titreq)
                lstjsonreq.append(jsonreq)
                lstexpectresq.append(expectresq)

                ttk.Button(frm_json_case_button, width="20", text=titreq, command=lambda lblexp=lblexpect, reqtxt=reqst_input, cont=cont: ChangConfWI(int(cont),reqtxt,lblexp)).grid(column=0, row=rowcont, padx=10, pady=10)
                rowcont += 1

            cont += 1

        return lsttiporeq, lsttitreq, lstjsonreq, lstexpectresq, reqst_input, lblexpect, resp_json_input,resp_kiblog



    def ChangConfWI(tipreq,reqtxt,lblexp):
    #try:
        reqtxt.delete('1.0', END)
        lblexp.delete('1.0', END)
        reqtxt.insert(tk.INSERT, lstjsonreq[tipreq])
        lblexp.insert(tk.INSERT, str(lstexpectresq[tipreq]))
    #except Exception as e:
     #   from OCPP.main import log_error
      #  log_error(e, "ChangConfWI")>


    def runpost(resp_json,reqtxt,tiporeq):
        try:
            getconfval = reqtxt.get(1.0, "end-1c")
            if len(getconfval)>1:
                resp_json.delete('1.0', END)
                resp_json.insert(tk.INSERT, str(url_endpoint+tiporeq)+", headers="+str(headers)+", data=json.dumps("+str(getconfval)+"), timeout="+str(timeoutvar)+"\n\n\n")
                reqjson = requests.request("POST", str(url_endpoint+tiporeq), headers=headers, data=json.dumps(getconfval), timeout=int(timeoutvar))
                statReason = ("Request:\n\n" + getconfval + "\n\nStatus:\n\n" + str(reqjson.status_code) + " - " + str(reqjson.reason) + "\n\nResponse:\n\n" + str(reqjson.text))
                resp_json.insert(tk.INSERT, statReason)

        except Exception as e:
           from OCPP.main import log_error
           resp_json.insert(tk.INSERT, "\n\n"+str(e)+"\n\n")
           log_error(e, "runpost")









#######Gera tabuladores##################################


    tabControl = ttk.Notebook(tabmain1)
#tab1
    tab1 = ttk.Frame(tabControl)
    tabControl.add(tab1, text="Messages")

#tab2
    tab2 = ttk.Frame(tabControl)
    tabControl.add(tab2, text='Change ')
    tabControl.pack(expand=1, fill="both")

    # Tab3
    tab3 = ttk.Frame(tabControl)
    tabControl.add(tab3, text=' Cache')
    tabControl.pack(expand=1, fill="both")

    # Tab4
    tab4 = ttk.Frame(tabControl)
    tabControl.add(tab4, text=' Configuration')
    tabControl.pack(expand=1, fill="both")

    # Tab5
    tab5 = ttk.Frame(tabControl)
    tabControl.add(tab5, text='Get ')
    tabControl.pack(expand=1, fill="both")

    # Tab6
    tab6 = ttk.Frame(tabControl)
    tabControl.add(tab6, text='List')
    tabControl.pack(expand=1, fill="both")

    # Tab7
    tab7 = ttk.Frame(tabControl)
    tabControl.add(tab7, text=' Start ')
    tabControl.pack(expand=1, fill="both")

    # Tab8
    tab8 = ttk.Frame(tabControl)
    tabControl.add(tab8, text=' Stop ')
    tabControl.pack(expand=1, fill="both")

    # Tab9
    tab9 = ttk.Frame(tabControl)
    tabControl.add(tab9, text='Reset')
    tabControl.pack(expand=1, fill="both")

    # tab10
    tab10 = ttk.Frame(tabControl)
    tabControl.add(tab10, text='Local')
    tabControl.pack(expand=1, fill="both")

    # tab11
    tab11 = ttk.Frame(tabControl)
    tabControl.add(tab11, text='Unlock ')
    tabControl.pack(expand=1, fill="both")

    # tab12
    tab12 = ttk.Frame(tabControl)
    tabControl.add(tab12, text='Update ')
    tabControl.pack(expand=1, fill="both")


    ############################################################################################################


    ################################################# tab1

    frmbtnspecs = ttk.Frame(tab1)
    frmbtnspecs.pack(side="top")

    lbl = Label(frmbtnspecs, width=8, text="Vendor:", justify=RIGHT, anchor="e").grid(row=0, column=0, sticky=W, pady=2)
    inp_cond_vendor = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_vendor.grid(row=0, column=1, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=20, text="chargeBoxSerialNumber:", justify=RIGHT, anchor="e").grid(row=0, column=2, sticky=W, pady=2)
    inp_cond_sn = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_sn.grid(row=0, column=3, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=8, text="Model:", justify=RIGHT, anchor="e").grid(row=0, column=4, sticky=W, pady=2)
    inp_cond_model = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_model.grid(row=0, column=5, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=16, text="Firmware Version:", justify=RIGHT, anchor="e").grid(row=0, column=6, sticky=W, pady=2)
    inp_cond_firmware = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_firmware.grid(row=0, column=7, sticky=NW, pady=2)

    frmbtn = ttk.Frame(tab1)
    frmbtn.pack(side="top", expand=1, fill="both")

    coll = int(0)
    specvar = int(1)

    var_expect_result = open("/Users/ricardosimoes/PycharmProjects/pythonProject/OCP/Confs/expectresult.txt", "r").readlines()
    for line in var_expect_result:
            x, y, y1 ,y2 ,y3 ,y4 ,y5 = line.split('<->')
            y_respexpt=(y+"\n\n"+y1+"\n\n"+y2+"\n\n"+y3+"\n\n"+y4+"\n\n"+y5).replace(' ', '').strip()
            lbl = Label(frmbtn, text=x.replace(' ', '').strip()).grid(column=coll, row=0, padx=10, pady=10)
            lbl = Label(frmbtn, text="Response / OBS:").grid(column=coll, row=1, padx=10, pady=10)
            kiblogbn = ScrolledText(frmbtn, width=25, height=20)
            kiblogbn.grid(column=coll, row=2, padx=10, pady=10, ipady=25)
            ttk.Button(frmbtn, width="5", text="OK", image=photoOK).grid(column=coll, row=3, padx=1, pady=1)
            ttk.Button(frmbtn, width="5", text="Not Ok", image=photoNot).grid(column=coll, row=4, padx=1, pady=1)
            lblspec = Label(frmbtn, text=y_respexpt, justify='left', anchor=N)
            lblspec.grid(column=coll, row=5, rowspan=55, sticky=N, padx=20, pady=20)
            coll += 1
            specvar += 1






    ########## FIM tab1 ################ FIM tab1 ################ FIM tab1 ############ FIM tab1 ############ FIM tab1




    makesubmenu("Change",tab2)

    makesubmenu("Cache",tab3)

    makesubmenu("Get",tab4)

    makesubmenu("something", tab5)





###########################################FIM nova janela####################################
gera_forms("stat1","nome_end<:>30<:>http://something.com")

if __name__ == "__main__":
    tabmain1.mainloop()

OK, I have the whole program now, but there's still a problem. There are five different files which it reads from, three of which are PNG images.

  • img/run.png
  • img/ok.png
  • img/notok.png
  • Confs/json_dumps.txt
  • Confs/expectresult.txt

(In the code, these are actually all hard-coded absolute paths, though it seems straightforward enough to reset these as relative paths.)

It would be easy for me to replace the images with something suitable, but I would need the specific files for the other two. The easiest solution would be for you to attach all five of them in a post.

hope this can help.

the absolute path is something, it didnt start like that but then i add a little function to backups the txt´s and they stop working. ill get to it latter, like you say its probable nothing.

thanks

run.png

ok.png

OK, thank you for those. I'll have to go over this to see what I can recommend.

commented: thank you :) +1

Even seeing it run, I'm still not certain what the program is for. Could you elaborate on what it is meant to be used for, please?

commented: . +0

the submenu have options of json request, the the request is show in Request and expected response in expected response, when you run the post it will output to response of the json request and then theres is a box for comments.

the messages tab is a diferent thing, you can ignore it

So it is basically a program to test JSON queries? Or is there something more to it?

commented: yes basicly that, but the querys are already defined in the txt +0

OK, so I have some changes to the code, but they are still rather kludgey. I can keep working on it, but I think it should do what you want now, at least.

import os
import time
from tkinter import *
import tkinter as tk
from tkinter import ttk, PhotoImage, LabelFrame, Text, GROOVE, Button, Label, scrolledtext
from tkinter.scrolledtext import ScrolledText
import requests
import json


def runpost(resp_json,reqtxt,tiporeq):
    try:
        getconfval = reqtxt.get(1.0, "end-1c")
        if len(getconfval)>1:
            resp_json.delete('1.0', END)
            resp_json.insert(tk.INSERT, str(url_endpoint+tiporeq)+", headers="+str(headers)+", data=json.dumps("+str(getconfval)+"), timeout="+str(timeoutvar)+"\n\n\n")
            reqjson = requests.request("POST", str(url_endpoint+tiporeq), headers=headers, data=json.dumps(getconfval), timeout=int(timeoutvar))
            statReason = ("Request:\n\n" + getconfval + "\n\nStatus:\n\n" + str(reqjson.status_code) + " - " + str(reqjson.reason) + "\n\nResponse:\n\n" + str(reqjson.text))
            resp_json.insert(tk.INSERT, statReason)

    except Exception as e:
        from OCPP.main import log_error
        resp_json.insert(tk.INSERT, "\n\n"+str(e)+"\n\n")
        log_error(e, "runpost")


    def ChangConfWI(tipreq,reqtxt,lblexp):
    #try:
        reqtxt.delete('1.0', END)
        lblexp.delete('1.0', END)
        reqtxt.insert(tk.INSERT, lstjsonreq[tipreq])
        lblexp.insert(tk.INSERT, str(lstexpectresq[tipreq]))
    #except Exception as e:
     #   from OCPP.main import log_error
      #  log_error(e, "ChangConfWI")


def generateTabs(tabControl, tabMenus):
    tab = list()
    for i, key in enumerate(tabMenus.keys()):
        tab.append(ttk.Frame(tabControl))
        tabControl.add(tab[i], text=key)
        ttk.Label(tab[i], text=tabMenus[key])
    tabControl.pack(expand=1, fill="both")    
    return tab


###########################################nova janela####################################

def gera_forms(parent, get_inp_cond_id, get_inp_cond_endpoint):
    parent.pack_forget()

    nome_endpoint, timeoutvar, url_endpoint = get_inp_cond_endpoint.split('<:>')
    nome_endpoint = nome_endpoint.replace('  ', '').strip()
    url_endpoint = url_endpoint.replace(' ', '').strip()
    timeoutvar = timeoutvar.replace(' ', '').strip()

    photoRun = PhotoImage(file=r'img/run.png')
    photoOK = PhotoImage(file=r'img/ok.png')
    photoNot = PhotoImage(file=r'img/notok.png')

    headers = {'Content-Type': 'application/json', 'chargingstation':'stat1'}

    tiporeq = ""
    payload = json.dumps({})
    expResp = ""

    varconfbook = open("Confs/json_dumps.txt", "r").readlines()
    lsttiporeq = []
    lsttitreq = []
    lstjsonreq = []
    lstexpectresq = []

    tab = []

    def makesubmenu(tipo_de_conf, framename):

        frm_json_case_button = ttk.Frame(framename)
        frm_json_case_button.grid(column=0, row=0, rowspan=99)

        frm_txt_json_case = ttk.Frame(framename)
        frm_txt_json_case.grid(column=1, row=0)

        url_show=ttk.Label(frm_txt_json_case, text=nome_endpoint + "  @  " + str(url_endpoint + tipo_de_conf) + "  @  " + get_inp_cond_id)
        url_show.grid(column=1, row=0, columnspan=99, padx=10, pady=10)

        ttk.Label(frm_txt_json_case, text="Request:").grid(column=2, row=1, padx=10, pady=10)
        reqst_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        reqst_input.grid(column=2, row=2, padx=10, pady=10, ipady=35)

        ttk.Label(frm_txt_json_case, text="Expected Response:").grid(column=2, row=3, rowspan=1, padx=10, pady=10)
        lblexpect = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        lblexpect.grid(column=2, row=4, padx=10, pady=10, ipady=15)

        resp_json_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        resp_json_input.grid(column=4, row=2, padx=10, pady=10, ipady=35)

        ttk.Button(frm_txt_json_case, text="Run", image=photoRun,command=lambda resp_json=resp_json_input, reqtxt=reqst_input, tiporeq=tipo_de_conf: runpost(resp_json, reqtxt, tiporeq)).grid(column=3, row=2, padx=10, pady=10, ipady=65)
        ttk.Label(frm_txt_json_case, text="Response:").grid(column=4, row=1, padx=10, pady=10)
        ttk.Label(frm_txt_json_case, text="Response / OBS:").grid(column=3, row=3, columnspan=5, padx=10, pady=10)
        resp_kiblog = ScrolledText(frm_txt_json_case, width=95, height=10)
        resp_kiblog.grid(column=3, row=4, padx=10, columnspan=5, rowspan=10, pady=10, ipady=120)

        frm_but_oknot = ttk.Frame(frm_txt_json_case)
        frm_but_oknot.grid(column=2, row=5, padx=1, pady=1)

        ttk.Button(frm_but_oknot, width="15", text="OK", image=photoOK, command=lambda: savetoxls(jsonresponse)).grid(column=0, row=0,padx=1, pady=15)
        ttk.Button(frm_but_oknot, width="15", text="Not Ok", image=photoNot).grid(column=1, row=0, padx=1, pady=15)

        rowcont = 0
        for cont, line in enumerate(varconfbook):
            if tipo_de_conf in line:
                tabbxx, tiporeq, titreq, jsonreq, expectresq = line.split('<->')
                lsttiporeq.append(tiporeq)
                lsttitreq.append(titreq)
                lstjsonreq.append(jsonreq)
                lstexpectresq.append(expectresq)

                ttk.Button(frm_json_case_button, width="20", text=titreq, command=lambda lblexp=lblexpect, reqtxt=reqst_input, cont=cont: ChangConfWI(int(cont),reqtxt,lblexp)).grid(column=0, row=rowcont, padx=10, pady=10)
                rowcont += 1

        return lsttiporeq, lsttitreq, lstjsonreq, lstexpectresq, reqst_input, lblexpect, resp_json_input,resp_kiblog



    #######Gera tabuladores##################################
    tabControl = ttk.Notebook(tabmain1)
    tabMenus = dict()
    tablist = open("Confs/tabs.txt", "r").readlines()
    tab = list()
    tabnames = list()
    for i, line in enumerate(tablist):
        title, data, option = line.split('<->')    
        tabMenus[title] = data     
        tabnames.append(title)

    tab = generateTabs(tabControl, tabMenus)


    ################################################# tab1

    frmbtnspecs = ttk.Frame(tab[0])
    #frmbtnspecs.pack(side="top")
    lbl = Label(frmbtnspecs, width=8, text="Vendor:", justify=RIGHT, anchor="e").grid(row=0, column=0, sticky=W, pady=2)
    inp_cond_vendor = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_vendor.grid(row=0, column=1, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=20, text="chargeBoxSerialNumber:", justify=RIGHT, anchor="e").grid(row=0, column=2, sticky=W, pady=2)
    inp_cond_sn = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_sn.grid(row=0, column=3, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=8, text="Model:", justify=RIGHT, anchor="e").grid(row=0, column=4, sticky=W, pady=2)
    inp_cond_model = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_model.grid(row=0, column=5, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=16, text="Firmware Version:", justify=RIGHT, anchor="e").grid(row=0, column=6, sticky=W, pady=2)
    inp_cond_firmware = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_firmware.grid(row=0, column=7, sticky=NW, pady=2)


    frmbtn = ttk.Frame(tab[0])
    frmbtn.pack(side="top", expand=1, fill="both")


    var_expect_result = open("Confs/expectresult.txt", "r").readlines()
    for coll, line in enumerate(var_expect_result):
            x, y, y1 ,y2 ,y3 ,y4 ,y5 = line.split('<->')
            y_respexpt=(y+"\n\n"+y1+"\n\n"+y2+"\n\n"+y3+"\n\n"+y4+"\n\n"+y5).replace(' ', '').strip()
            lbl = Label(frmbtn, text=x.replace(' ', '').strip()).grid(column=coll, row=0, padx=10, pady=10)
            lbl = Label(frmbtn, text="Response / OBS:").grid(column=coll, row=1, padx=10, pady=10)
            kiblogbn = ScrolledText(frmbtn, width=25, height=20)
            kiblogbn.grid(column=coll, row=2, padx=10, pady=10, ipady=25)
            ttk.Button(frmbtn, width="5", text="OK", image=photoOK).grid(column=coll, row=3, padx=1, pady=1)
            ttk.Button(frmbtn, width="5", text="Not Ok", image=photoNot).grid(column=coll, row=4, padx=1, pady=1)
            lblspec = Label(frmbtn, text=y_respexpt, justify='left', anchor=N)
            lblspec.grid(column=coll, row=5, rowspan=55, sticky=N, padx=20, pady=20)

    for i in range(1, len(tabnames)):
        makesubmenu(tabnames[i], tab[i])



###########################################FIM nova janela####################################

if __name__ == "__main__":
    tabmain1 = Tk()
    w, h = tabmain1.winfo_screenwidth(), tabmain1.winfo_screenheight()
    tabmain1.geometry("%dx%d+0+0" % (w, h))

    frmmain = Label(tabmain1, text='')
    frmmain.pack(side='top', fill='x', expand=False)

    gera_forms(frmmain, "stat1","nome_end<:>30<:>http://something.com")

    tabmain1.mainloop()

Made a small change since there is no need for the tabs.txt since that info is in json_dumps.txt

import os
import time
from tkinter import *
import tkinter as tk
from tkinter import ttk, PhotoImage, LabelFrame, Text, GROOVE, Button, Label, scrolledtext
from tkinter.scrolledtext import ScrolledText
import requests
import json


def runpost(resp_json,reqtxt,tiporeq):
    try:
        getconfval = reqtxt.get(1.0, "end-1c")
        if len(getconfval)>1:
            resp_json.delete('1.0', END)
            resp_json.insert(tk.INSERT, str(url_endpoint+tiporeq)+", headers="+str(headers)+", data=json.dumps("+str(getconfval)+"), timeout="+str(timeoutvar)+"\n\n\n")
            reqjson = requests.request("POST", str(url_endpoint+tiporeq), headers=headers, data=json.dumps(getconfval), timeout=int(timeoutvar))
            statReason = ("Request:\n\n" + getconfval + "\n\nStatus:\n\n" + str(reqjson.status_code) + " - " + str(reqjson.reason) + "\n\nResponse:\n\n" + str(reqjson.text))
            resp_json.insert(tk.INSERT, statReason)

    except Exception as e:
        from OCPP.main import log_error
        resp_json.insert(tk.INSERT, "\n\n"+str(e)+"\n\n")
        log_error(e, "runpost")


    def ChangConfWI(tipreq,reqtxt,lblexp):
    #try:
        reqtxt.delete('1.0', END)
        lblexp.delete('1.0', END)
        reqtxt.insert(tk.INSERT, lstjsonreq[tipreq])
        lblexp.insert(tk.INSERT, str(lstexpectresq[tipreq]))
    #except Exception as e:
     #   from OCPP.main import log_error
      #  log_error(e, "ChangConfWI")


def generateTabs(tabControl, tabMenus):
    tab = list()
    for i, key in enumerate(tabMenus.keys()):
        tab.append(ttk.Frame(tabControl))
        tabControl.add(tab[i], text=key)
        ttk.Label(tab[i], text=tabMenus[key])
    tabControl.pack(expand=1, fill="both")
    return tab


###########################################nova janela####################################

def gera_forms(parent, get_inp_cond_id, get_inp_cond_endpoint):
    parent.pack_forget()

    nome_endpoint, timeoutvar, url_endpoint = get_inp_cond_endpoint.split('<:>')
    nome_endpoint = nome_endpoint.replace('  ', '').strip()
    url_endpoint = url_endpoint.replace(' ', '').strip()
    timeoutvar = timeoutvar.replace(' ', '').strip()

    photoRun = PhotoImage(file=r'img/run.png')
    photoOK = PhotoImage(file=r'img/ok.png')
    photoNot = PhotoImage(file=r'img/notok.png')

    headers = {'Content-Type': 'application/json', 'chargingstation':'stat1'}

    tiporeq = ""
    payload = json.dumps({})
    expResp = ""

    varconfbook = open("Confs/json_dumps.txt", "r").readlines()
    lsttiporeq = []
    lsttitreq = []
    lstjsonreq = []
    lstexpectresq = []

    tab = []

    def makesubmenu(tipo_de_conf, framename):

        frm_json_case_button = ttk.Frame(framename)
        frm_json_case_button.grid(column=0, row=0, rowspan=99)

        frm_txt_json_case = ttk.Frame(framename)
        frm_txt_json_case.grid(column=1, row=0)

        url_show=ttk.Label(frm_txt_json_case, text=nome_endpoint + "  @  " + str(url_endpoint + tipo_de_conf) + "  @  " + get_inp_cond_id)
        url_show.grid(column=1, row=0, columnspan=99, padx=10, pady=10)

        ttk.Label(frm_txt_json_case, text="Request:").grid(column=2, row=1, padx=10, pady=10)
        reqst_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        reqst_input.grid(column=2, row=2, padx=10, pady=10, ipady=35)

        ttk.Label(frm_txt_json_case, text="Expected Response:").grid(column=2, row=3, rowspan=1, padx=10, pady=10)
        lblexpect = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        lblexpect.grid(column=2, row=4, padx=10, pady=10, ipady=15)

        resp_json_input = ScrolledText(frm_txt_json_case, width=75, height=10, wrap=tk.WORD)
        resp_json_input.grid(column=4, row=2, padx=10, pady=10, ipady=35)

        ttk.Button(frm_txt_json_case, text="Run", image=photoRun,command=lambda resp_json=resp_json_input, reqtxt=reqst_input, tiporeq=tipo_de_conf: runpost(resp_json, reqtxt, tiporeq)).grid(column=3, row=2, padx=10, pady=10, ipady=65)
        ttk.Label(frm_txt_json_case, text="Response:").grid(column=4, row=1, padx=10, pady=10)
        ttk.Label(frm_txt_json_case, text="Response / OBS:").grid(column=3, row=3, columnspan=5, padx=10, pady=10)
        resp_kiblog = ScrolledText(frm_txt_json_case, width=95, height=10)
        resp_kiblog.grid(column=3, row=4, padx=10, columnspan=5, rowspan=10, pady=10, ipady=120)

        frm_but_oknot = ttk.Frame(frm_txt_json_case)
        frm_but_oknot.grid(column=2, row=5, padx=1, pady=1)

        ttk.Button(frm_but_oknot, width="15", text="OK", image=photoOK, command=lambda: savetoxls(jsonresponse)).grid(column=0, row=0,padx=1, pady=15)
        ttk.Button(frm_but_oknot, width="15", text="Not Ok", image=photoNot).grid(column=1, row=0, padx=1, pady=15)

        rowcont = 0
        for cont, line in enumerate(varconfbook):
            if tipo_de_conf in line:
                tabbxx, tiporeq, titreq, jsonreq, expectresq = line.split('<->')
                lsttiporeq.append(tiporeq)
                lsttitreq.append(titreq)
                lstjsonreq.append(jsonreq)
                lstexpectresq.append(expectresq)

                ttk.Button(frm_json_case_button, width="20", text=titreq, command=lambda lblexp=lblexpect, reqtxt=reqst_input, cont=cont: ChangConfWI(int(cont),reqtxt,lblexp)).grid(column=0, row=rowcont, padx=10, pady=10)
                rowcont += 1

        return lsttiporeq, lsttitreq, lstjsonreq, lstexpectresq, reqst_input, lblexpect, resp_json_input,resp_kiblog



    #######Gera tabuladores##################################
    tabControl = ttk.Notebook(tabmain1)
    tabMenus = dict()
    tab = list()
    tabnames = list()
    for i, line in enumerate(varconfbook):
        title, data, option, dfdd, ffes = line.split('<->')
        tabMenus[title] = data
        tabnames.append(title)

    tab = generateTabs(tabControl, tabMenus)


    ################################################# tab1

    frmbtnspecs = ttk.Frame(tab[0])
    #frmbtnspecs.pack(side="top")
    lbl = Label(frmbtnspecs, width=8, text="Vendor:", justify=RIGHT, anchor="e").grid(row=0, column=0, sticky=W, pady=2)
    inp_cond_vendor = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_vendor.grid(row=0, column=1, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=20, text="chargeBoxSerialNumber:", justify=RIGHT, anchor="e").grid(row=0, column=2, sticky=W, pady=2)
    inp_cond_sn = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_sn.grid(row=0, column=3, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=8, text="Model:", justify=RIGHT, anchor="e").grid(row=0, column=4, sticky=W, pady=2)
    inp_cond_model = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_model.grid(row=0, column=5, sticky=NW, pady=2)

    lbl = Label(frmbtnspecs, width=16, text="Firmware Version:", justify=RIGHT, anchor="e").grid(row=0, column=6, sticky=W, pady=2)
    inp_cond_firmware = Text(frmbtnspecs, height=1, width=35, relief=GROOVE, borderwidth=2)
    inp_cond_firmware.grid(row=0, column=7, sticky=NW, pady=2)


    frmbtn = ttk.Frame(tab[0])
    frmbtn.pack(side="top", expand=1, fill="both")


    var_expect_result = open("Confs/expectresult.txt", "r").readlines()
    for coll, line in enumerate(var_expect_result):
            x, y, y1 ,y2 ,y3 ,y4 ,y5 = line.split('<->')
            y_respexpt=(y+"\n\n"+y1+"\n\n"+y2+"\n\n"+y3+"\n\n"+y4+"\n\n"+y5).replace(' ', '').strip()
            lbl = Label(frmbtn, text=x.replace(' ', '').strip()).grid(column=coll, row=0, padx=10, pady=10)
            lbl = Label(frmbtn, text="Response / OBS:").grid(column=coll, row=1, padx=10, pady=10)
            kiblogbn = ScrolledText(frmbtn, width=25, height=20)
            kiblogbn.grid(column=coll, row=2, padx=10, pady=10, ipady=25)
            ttk.Button(frmbtn, width="5", text="OK", image=photoOK).grid(column=coll, row=3, padx=1, pady=1)
            ttk.Button(frmbtn, width="5", text="Not Ok", image=photoNot).grid(column=coll, row=4, padx=1, pady=1)
            lblspec = Label(frmbtn, text=y_respexpt, justify='left', anchor=N)
            lblspec.grid(column=coll, row=5, rowspan=55, sticky=N, padx=20, pady=20)

    for i in range(1, len(tabnames)):
        makesubmenu(tabnames[i], tab[i])



###########################################FIM nova janela####################################

if __name__ == "__main__":
    tabmain1 = Tk()
    w, h = tabmain1.winfo_screenwidth(), tabmain1.winfo_screenheight()
    tabmain1.geometry("%dx%d+0+0" % (w, h))

    frmmain = Label(tabmain1, text='')
    frmmain.pack(side='top', fill='x', expand=False)

    gera_forms(frmmain, "stat1","nome_end<:>30<:>http://something.com")

    tabmain1.mainloop()

json_dumps.txt
tab_number<->name/text_of_tab<->text_of_button<->json_request<->espected_response

ex:

tab1<->confs<->btn1<->{}<->expected response1 for confs
tab1<->confs<->btn2<->{}<->expected response2 for confs
tab2<->cache<->btn1<->{}<->expected response1 for cache
tab3<->gets<->btn1<->{}<->expected response1 for gets

>   File "/Users/ricardosimoes/PycharmProjects/pythonProject/OCP/old_gera.py", line 132, in gera_forms
>     title, data, option, dfdd, ffes = line.split('<->')
> ValueError: not enough values to unpack (expected 5, got 1)
> 

this is strange because i change it to fetch the 5 vars, even thou its not gona use it

any idea?

OK, I am still looking into this, and while I haven't really made much progress, one thing that strikes me is that you could use a comprehensive data structure to hold the data in 'json_dumps.txt'. Also, the 'json_dumps.txt' file itself is a bit poorly normalized, since you don't really need both the index number of the tab, and the tab title; just the title should be sufficient.

I've written a function to destructure the file data into a dictionary keyed on the title, where each entry is a list which in turn contains one or more dictionaries representing that tab's button controls. However, using it effectively may require a lager restructing of the program as a whole, which I'd have to help you with later.

def packComparisonData(test_file):
    """Destructures a list of lines into a dictionary keyed on the title
    of the tab, each entry of which containing a list of sub-dictionaries
    holding the name of the button to be created, the corresponding
    JSON request to be performed, and the expected results of the 
    given request."""
    comp_entries = dict()
    for line in test_file:
        tab_title, button_name, json_request, expected_response = line.split('<->')
        if tab_title not in comp_entries.keys():
            comp_entries[tab_title] = list()
        comp_entries[tab_title].append({
                                    "button_name": button_name,
                                    "json_request": json_request,
                                    "expected_response": expected_response})
    return comp_entries

Oddly enough, I have continued experimenting on this, and expanded on the earlier work by replacing the ad-hoc data structure used previousl.y with a set of classes (including two types of exceptions) representing the data explicitly. There is a small test program at the end of the file to show how it can be used.

from tkinter import *
import tkinter as tk
from tkinter import ttk, Label


class TabSet(ttk.Notebook):
    def __init__(self, root, parent):
        super().__init__(root)
        self.root = root
        self.parent = parent
        self.tabEntries = dict()

    def add(self, title, **kwargs):
        if title not in self.tabEntries.keys():
            self.tabEntries[title] = TabEntry(title)
        if "tab" in kwargs.keys():
            if self.tabEntries[title].tab != None:
                raise TabSetDuplicateTabException(title)
            else:
                self.tabEntries[title].tab = kwargs["tab"]
                super().add(self.tabEntries[title].tab, text=title)
        if "subentry" in kwargs.keys():
            self.tabEntries[title].add(kwargs["subentry"])
            if "button_name" in kwargs.keys() and "json_request" in kwargs.keys() and "expected_response" in kwargs.keys():    
                self.tabEntries[title][kwargs["button_name"]] = TabSubentry(kwargs["button_name"], kwargs["json_request"], kwargs["expected_response"])



class TabEntry:
    def __init__(self, tab_title):
        self.tab_title = tab_title
        self.tab = None
        self.subentries = dict()

    def add(self, subentry):
        if subentry.button_name not in self.subentries.keys():
            self.subentries[subentry.button_name] = subentry
        else:
            raise TabEntryDuplicateSubentryException(self.tab_title, subentry.button_name)


class TabSubentry:
    def __init__(self, button_name, json_request, expected_response):
        self.button_name = button_name
        self.json_request = json_request
        self.expected_response = expected_response


class TabSetDuplicateTabException(Exception):
    def __init__(self, title):
        self.title = title


class TabEntryDuplicateSubentryException(Exception):
    def __init__(self, title, button):
        self.title = title
        self.button = button


if __name__ == "__main__":
    root = tk.Tk()
    root.title("Tab Widget")
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (w, h))
    frame = Label(root, text='')
    frame.pack(side='top', fill='x', expand=False)    
    tabControl = TabSet(root, frame)
    tabControl.add("Tab 1", 
                   tab = ttk.Frame(tabControl),  
                   button="Button 1", json_request="{}", expected_response="")
    ttk.Label(tabControl.tabEntries["Tab 1"].tab, text="Button 1")
    tabControl.add("Tab 2", subentry=TabSubentry("Button A", "{foo}", "foo"))
    ttk.Label(tabControl.tabEntries["Tab 2"].tab, text="Button A")
    tabControl.add("Tab 2", tab = tk.Frame(tabControl))
    ttk.Label(tabControl.tabEntries["Tab 2"].tab, text="Button B")

    try:
        tabControl.add("Tab 2", tab = tk.Frame(tabControl))
        ttk.Label(tabControl.tabEntries["Tab 2"].tab, text="Button B")
    except(TabSetDuplicateTabException) as exp:
        print("Duplicate tab {0}".format(exp.title))

    try:
        tabControl.add("Tab 2", subentry=TabSubentry("Button A", "{foo}", "foo"))
        ttk.Label(tabControl.tabEntries["Tab 2"].tab, text="Button B")       
    except(TabEntryDuplicateSubentryException) as exp:
        print("Duplicate button {0} in tab {1}".format(exp.button, exp.title))

    tabControl.pack(expand=1, fill="both")       
    root.mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.