Demo entry 3520980

Controller

   

Submitted by anonymous on Jan 08, 2016 at 16:25
Language: Python 3. Code size: 25.6 kB.

from tkinter import *
from tkinter import ttk


import mysql.connector

root = Tk()
root.minsize(800, 480)

root.overrideredirect(1)
global firstclick
firstclick = "Y"


def pgmselect(localschedkey, FireType):

    global orow
    global SchedKey
    global tree

    SchedKey = localschedkey

    def FQuit():
        frame1.destroy()
        firepgm()

    def FSave(sc):
        global SchedKey  # schedkey is the unique key for schedulemaster and parent key for steps
        global tree
        # update tree with data from last row clicked  (using tree as array for
        # current schedule)
        tree.item(
            (orow),
            values=(
                currentstep,
                RateEntry.get(),
                TargetEntry.get(),
                HoldEntry.get(),
                AlarmEntry.get()))

        cnx = mysql.connector.connect(user='cadmin', password='pi',
                                      host='localhost',
                                      database='controller')
        cursor = cnx.cursor()

# in the save routine we need to open the database and replace the edited program
# first delete all rows for selected schedule
        qry = 'delete from TSchedSteps where SchedKey=' + str(sc)
        cursor.execute(qry)
        cnx.commit()

        for child in tree.get_children():
            # need sql statement for each item in the tree

            qry = 'insert into TSchedSteps VALUES (' + str(sc) + ',' + str(tree.item(child)['values'][0]) + ',' + str(tree.item(child)['values'][
                1]) + ',' + str(tree.item(child)['values'][2]) + ',' + str(tree.item(child)['values'][3]) + ',' + str(tree.item(child)['values'][3]) + ')'
            print (qry)
            cursor.execute(qry)
            cnx.commit()

        # now insert tree values

        cursor.close()
        cnx.close

    def Bclear():
        # Clear all the entry boxes
        RateEntry['state'] = NORMAL
        TargetEntry['state'] = NORMAL
        HoldEntry['state'] = NORMAL
        AlarmEntry['state'] = NORMAL

    # set the colors

        RateEntryValue = ''
        TargetEntryValue = ''
        HoldEntryValue = ''
        AlarmEntryValue = ''

        RateEntry['state'] = DISABLED
        TargetEntry['state'] = DISABLED
        HoldEntry['state'] = DISABLED
        AlarmEntry['state'] = DISABLED
        Abox = ''

    def Msgout(msgtext, mcolor):
        Msgline['state'] = NORMAL
        Msgline.delete(0.0, END)
        Msgline['foreground'] = mcolor
        Msgline.insert(END, msgtext)
        Msgline['state'] = DISABLED

    def Bname(box, stepvar, mcolor):
        global Abox
        Abox = box

    # First check box and
        # print message at bottom

    # Now highlight data entry box and verify state of all boxes

        # change all to white and then highlight entry box
        RateEntry['bg'] = 'white'
        RateEntry['disabledbackground'] = 'white'
        TargetEntry['bg'] = 'white'
        HoldEntry['bg'] = 'white'
        AlarmEntry['bg'] = 'white'
        cmdstring = Abox + '["bg"]="yellow"'
        exec(cmdstring)
        cmdstring = Abox + '["disabledbackground"]="yellow"'
        exec (cmdstring)
        Msgout(stepvar, mcolor)

    def click(key):
        global Abox
        global memory
        global RateEntryValue
        global TargetEntryValue
        global HoldEntryValue
        global AlarmEntryValue

    # Check for active box
    # if no button pushed print message at bottom
        if len(Abox) == 0:
            Msgout('Select a step variable', 'red')
            return()

    # Work with number entry
        str1 = "-+0123456789."
        if key in str1:
            # first enable the box for entry
            cmdstring = Abox + '["state"] = NORMAL'
            exec (cmdstring)
            cmdstring = Abox + '.insert(END,key)'
            exec (cmdstring)
            cmdstring = Abox + '["state"] = DISABLED'
            exec (cmdstring)
    # check for backspace key
        if key == '<':

            cmdstring = Abox + '["state"] = NORMAL'
            exec (cmdstring)
            code = 'len(' + Abox + '.get())'
            bval = eval(code)
            cmdstring = Abox + '.delete(' + str(bval - 1) + ',END)'
            exec (cmdstring)
            cmdstring = Abox + '["state"] = DISABLED'
            exec (cmdstring)

    # for every keypress update all of the box values.  Set to 0 if blank

        RateEntryValue = RateEntry.get()
        if RateEntryValue == '':
            RateEntryValue = 0
        else:
            RateEntryValue = int(RateEntryValue)

        TargetEntryValue = TargetEntry.get()

        if TargetEntryValue == '':
            TargetEntryValue = 0
        else:
            TargetEntryValue = int(TargetEntryValue)

        HoldEntryValue = HoldEntry.get()
        if HoldEntryValue == '':
            HoldEntryValue = 0
        else:
            HoldEntryValue = int(HoldEntryValue)

        AlarmEntryValue = AlarmEntry.get()
        if AlarmEntryValue == '':
            AlarmEntryValue = 0
        else:
            AlarmEntryValue = int(AlarmEntryValue)

        ########################################
    def refreshentry(sn, re, te, he, ae):
        global RateEntry
        global TargetEntry
        global HoldEntry
        global AlarmEntry
        global Msgline
        global Abox
        global SchedKey
        global FirePgm
        global StepNo
        global RateEntryValue
        global TargetEntryValue
        global HoldEntryValue
        global AlarmEntryValue
        # Insert tree values from selected row
        RateEntry['state'] = NORMAL
        RateEntry.delete(0, END)
        RateEntry.insert(0, str(re))
        RateEntryValue = re
        RateEntry['state'] = DISABLED
        #
        TargetEntry['state'] = NORMAL
        TargetEntry.delete(0, END)
        TargetEntry.insert(0, te)
        TargetEntryValue = te
        TargetEntry['state'] = DISABLED
        #
        HoldEntry['state'] = NORMAL
        HoldEntry.delete(0, END)
        HoldEntry.insert(0, he)
        HoldEntryValue = he
        HoldEntry['state'] = DISABLED
        #
        AlarmEntry['state'] = NORMAL
        AlarmEntry.delete(0, END)
        AlarmEntry.insert(0, ae)
        AlarmEntryValue = ae
        AlarmEntry['state'] = DISABLED

        # set the colors
        RateEntry['bg'] = 'white'
        TargetEntry['bg'] = 'white'
        HoldEntry['bg'] = 'white'
        AlarmEntry['bg'] = 'white'

        RateEntry['disabledbackground'] = 'white'
        TargetEntry['disabledbackground'] = 'white'
        HoldEntry['disabledbackground'] = 'white'
        AlarmEntry['disabledbackground'] = 'white'

        RateEntry['state'] = DISABLED
        TargetEntry['state'] = DISABLED
        HoldEntry['state'] = DISABLED
        AlarmEntry['state'] = DISABLED
        Abox = ''

        Bclear()

    def buildentry(sn, re, te, he, ae):
        global RateEntry
        global TargetEntry
        global HoldEntry
        global AlarmEntry
        global Msgline
        global Abox
        global SchedKey
        global FirePgm
        global StepNo
        global RateEntryValue
        global TargetEntryValue
        global HoldEntryValue
        global AlarmEntryValue

        frame2 = Frame(frame1, bg='grey', height=50, width=100, bd=10)
        frame2.pack(side=RIGHT, fill=BOTH)
        canvas = Canvas(frame1, width=200, height=240)
        canvas.pack()

        # Variables
        Abox = ""
        EndVar = ""
        if ae == 'None':
            ae = ''
        StepNo = sn

        RButton = Button(
            canvas,
            text="Rate",
            width=8,
            relief="raised",
            command=lambda: Bname(
                "RateEntry",
                "Enter Ramp Rate",
                "darkblue"))
        RButton.pack()
        RButton.place(x=20, y=40)
        TButton = Button(
            canvas,
            text="Target",
            width=8,
            relief="raised",
            command=lambda: Bname(
                "TargetEntry",
                "Enter Target Temperature",
                "darkblue"))
        TButton.pack()
        TButton.place(x=20, y=60)
        HButton = Button(
            canvas,
            text="Hold",
            width=8,
            relief="raised",
            command=lambda: Bname(
                "HoldEntry",
                "Enter Hold Time (Minutes)",
                "darkblue"))
        HButton.pack()
        HButton.place(x=20, y=80)
        AButton = Button(
            canvas,
            text="Alarm",
            width=8,
            relief="raised",
            command=lambda: Bname(
                "AlarmEntry",
                "Enter Alarm Temperature",
                "darkblue"))
        AButton.pack()
        AButton.place(x=20, y=100)
        SaveButton = Button(
            frame2,
            text='Save Program',
            command=lambda: FSave(SchedKey))
        SaveButton.pack()
        SaveButton.place(x=5, y=145)
        QuitButton = Button(frame2, text='Quit', command=lambda: FQuit())
        QuitButton.pack()
        QuitButton.place(x=5, y=170)

        RateEntry = Entry(canvas, width=9, bg='white', state=DISABLED,
                          disabledbackground='white', disabledforeground='black')
        TargetEntry = Entry(canvas, width=9, bg="white", state=DISABLED,
                            disabledbackground='white', disabledforeground='black')
        HoldEntry = Entry(canvas, width=9, bg="white", state=DISABLED,
                          disabledbackground='white', disabledforeground='black')
        AlarmEntry = Entry(canvas, width=9, bg="white", state=DISABLED,
                           disabledbackground='white', disabledforeground='black')

        RateEntry.place(x=90, y=41)
        TargetEntry.place(x=90, y=62)
        HoldEntry.place(x=90, y=83)
        AlarmEntry.place(x=90, y=104)
        refreshentry(sn, re, te, he, ae)

        Msgline = Text(
            canvas,
            height=1,
            width=30,
            bg='lightgrey',
            state=DISABLED)
        Msgline.place(x=10, y=220)

        btn_list = [
            '7', '8', '9',
            '4', '5', '6',
            '1', '2', '3',
            '0', '<', 'Q']
        # create all buttons with a loop
        r = 1
        c = 0
        for b in btn_list:
            rel = 'ridge'
            cmd = lambda x=b: click(x)
            Button(
                frame2,
                text=b,
                width=1,
                relief=rel,
                command=cmd).grid(
                row=r,
                column=c)

            c += 1
            if c > 2:
                c = 0
                r += 1

        frame2.pack()

    def changestep(evt):
        global firstclick
        global nrow
        global orow
        global curitem
        global StepNo
        global FirePgm
        global RateEntry
        global TargetEntry
        global HoldEntry
        global AlarmEntry
        global currentstep
        global SchedKey
        curitem = tree.focus()

        nrow = tree.focus()
        # skip this if focus is not on a row in the tree - do nothing
        if tree.focus() != '':

            if firstclick == 'Y':
                # save button in buildentry must reset row numbers and first
                # click
                # variablebuildentry(tree.item(curitem)["values"][0],tree.item(curitem)["values"][1],
                # tree.item(curitem)["values"][2],
                # tree.item(curitem)["values"][3],
                # tree.item(curitem)["values"][4])  #save button in buildentry
                # must reset row numbers and first click variable
                buildentry(
                    tree.item(curitem)["values"][0],
                    tree.item(curitem)["values"][1],
                    tree.item(curitem)["values"][2],
                    tree.item(curitem)["values"][3],
                    tree.item(curitem)["values"][4])
                firstclick = ''
                currentstep = tree.item(curitem)["values"][0]

            if nrow != orow:

                if orow != 'x':

                    print ('updating tree')
                    print (tree.item(orow))
                    tree.item(
                        (orow),
                        values=(
                            currentstep,
                            RateEntry.get(),
                            TargetEntry.get(),
                            HoldEntry.get(),
                            AlarmEntry.get()))

                orow = tree.focus()
                crow = tree.item(curitem)["values"]
                currentstep = tree.item(nrow)["values"][0]

                # refreshentry(currentstep,RateEntry.get(),
                # TargetEntry.get(),HoldEntry.get(), AlarmEntry.get()
                refreshentry(
                    tree.item(curitem)["values"][0],
                    tree.item(curitem)["values"][1],
                    tree.item(curitem)["values"][2],
                    tree.item(curitem)["values"][3],
                    tree.item(curitem)["values"][4])

    frame1 = Frame(root)
    frame1.pack()
    tree = ttk.Treeview(frame1)
    tree.bind("<ButtonRelease-1>", changestep)
    tree["columns"] = ("Step", "TTemp", "RRate", "HTime", "ATemp")
    tree.column("Step", width=40)
    tree.column("TTemp", width=100)
    tree.column("RRate", width=100)
    tree.column("HTime", width=100)
    tree.column("ATemp", width=100)
    tree.heading("Step", text="Step")
    tree.heading("TTemp", text="Target Temp")
    tree.heading("RRate", text="Ramp Rate")
    tree.heading("HTime", text="Hold Time")
    tree.heading("ATemp", text="Alarm Temp")
    tree.heading("#0", text="")
    tree.column("#0", width=0)
    cursor = cnx.cursor()
    qry = 'select SchedKey, StepNumber, TargetTemp, RampRate, HoldTime, AlarmTemp from TSchedSteps where SchedKey=' + \
        str(localschedkey) + ' order by Schedkey, StepNumber'
    cursor.execute(qry)

    for (SchedKey, StepNumber, TargetTemp,
         RampRate, HoldTime, AlarmTemp) in cursor:

        tree.insert(
            "",
            str(StepNumber),
            text=str(StepNumber),
            values=(
                str(StepNumber),
                str(TargetTemp),
                str(RampRate),
                str(HoldTime),
                str(AlarmTemp)))
    cursor.close()
    cnx.close
    listbox.pack_forget()

    label22 = Label(
        frame1,
        text='Schedule Name: ' +
        FireType +
        ' - ' +
        str(SchedKey),
        relief=RAISED)
    label22.pack()

    tree.pack()
    orow = 'x'


def pgmload(FireType):

    # screen to load list of programs for selected fire types and allow for
    # run, edit, clone or new

    global listbox
    global frame1
    global cnx
    global FirePgm
    global nrow
    global firstclick
    global framefire
    global pgmlist
    global MsglinePgm
    global PgmMsgout
    global FQuit
    global framepgmselect
    global longentry
    global shortentry

    framefire.pack_forget()
    framepgmselect = Frame(root, height=480, width=800)
    framepgmselect.pack(fill=NONE, expand=FALSE)
    listbox = Listbox(framepgmselect, height=10, width=80, selectmode=SINGLE)
    listbox.place(x=50, y=50)

# add buttons for programs
    framepgmbuttons1 = Frame(framepgmselect)
    framepgmbuttons1.place(x=50, y=210)
    framepgmbuttons2 = Frame(framepgmselect)
    framepgmbuttons2.place(x=120, y=240)
    ButtonFire = Button(
        framepgmbuttons1,
        text="Run Schedule",
        command=lambda: "Runmode")
    ButtonEdit = Button(
        framepgmbuttons1,
        text="Edit Schedule",
        command=lambda: editpgm())
    ButtonClone = Button(
        framepgmbuttons1,
        text="Clone Schedule",
        command=lambda: FClone(SchedKey))
    ButtonNewPgm = Button(
        framepgmbuttons2,
        text="New " + FireType + " Schedule",
        command=lambda: alphaboard())
    ButtonQuit = Button(
        framepgmbuttons2,
        text="Quit",
        command=lambda: QuitRoutine())
    ButtonFire.pack(side=LEFT)
    ButtonEdit.pack(side=LEFT)
    ButtonClone.pack(side=LEFT)
    ButtonNewPgm.pack(side=LEFT)
    ButtonQuit.pack(side=LEFT)

    MsglinePgm = Text(
        framepgmselect,
        height=1,
        width=80,
        bg='lightgrey',
        state=DISABLED)
    MsglinePgm.place(x=50, y=270)
    shortentry = Text(framepgmselect, width=40, height=1)
    longentry = Text(framepgmselect, width=40, height=3)

    # Connect to the database

    # empty array
    pgmlist = []
    cnx = mysql.connector.connect(user='cadmin', password='pi',
                                  host='localhost',
                                  database='controller')
    cursor = cnx.cursor()
    qry = 'select SchedKey, KilnNumber, SchedType, FireType, FireTypeNumber, SchedDescriptShort, SchedDescriptLong from TScheduleMaster where FireType = "' + FireType + '"'
    cursor.execute(qry)

    for (SchedKey, KilnNumber, SchedType, FireType, FireTypeNumber,
         SchedDescriptShort, SchedDescriptLong) in cursor:
        FirePgm = FireType + str(FireTypeNumber)

        listbox.insert(
            END,
            str(SchedKey) +
            ' ' +
            FireType +
            str(FireTypeNumber) +
            " " +
            SchedDescriptShort)
        # build a reference array for loaded sched masters
        pgmlist.append([SchedKey, SchedType])

    def QuitRoutine():
        framepgmselect.destroy()
        firepgm()
# don't close cursor for now
    cursor.close()
    cnx.close
    nrow = ''
    firstclick = 'Y'

    def PgmMsgout(msgtext, mcolor):
        global MsglinePgm
        print('in msgout')
        MsglinePgm['state'] = NORMAL
        MsglinePgm.delete(0.0, END)
        MsglinePgm['foreground'] = mcolor
        MsglinePgm.insert(END, msgtext)
        MsglinePgm['state'] = DISABLED

    def alphaboard(wbox):

        alphaframe = Frame(framepgmselect)
        alphaframe.place(x=400, y=300)
        abtn_list = [
            '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
            'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
            '', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
            '', '', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ''
        ]
        # create all buttons with a loop
        r = 1
        c = 0
        for b in abtn_list:
            rel = 'ridge'
            cmd = lambda x=b: aclick(x)
            Button(
                alphaframe,
                text=b,
                width=1,
                relief=rel,
                command=cmd).grid(
                row=r,
                column=c)

            c += 1
            if c > 9:
                c = 0
                r += 1

        def aclick(key, ebox):

            # Work with number entry
            str1 = "-+0123456789."
            if key in str1:
                # first enable the box for entry

                cmdstring = ebox + '.insert(END,key)'
                exec (cmdstring)

    # check for backspace key
            if key == '<':

                #code = 'len('+ebox+'.get())'
                #bval = eval(code)
                # not right  - need to go from current position in box
                # cmdstring = ebox+'.delete('0',END)'
                #exec (cmdstring)

    def FClone(sc):
        global framepgmselect
        global shortentry
        global longentry

        # for clone,
        # show alpha keyboard to allow entry of long and short description
        # get new schedule key by incrementing max schedkey from query
        # write a new schedule master record - for now use Kiln 1

        # read all rows from db for a schedule, find the next schedule number and write copy of rows into db.  Also
        # just build a list of strings for the values from the step
        # write records into TSchedSteps where to go from here - should be back
        # to pgmselect screen with refreshed list but how

        # capture new long and short descriptions

        # new frame for data entry and alpha board
        print ('a freamedesc')
        # framedesc.pack()

        #shortentry = Text(framedesc,width = 40, height = 1)
        #shortentry.place(x = 50, y = 300)
        ##longentry = Text(framedesc,width = 40,height = 3)
        #longentry.place(x = 50, y = 330)
        shortentry.place(x=50, y=300)
        longentry.place(x=50, y=350)
        # start with focus in the short but allow clicks to move focus and update
        # new button to complete close
        shortentry.focus()

        alphaboard('short')

        def updatedb(shortvalue, longvalue):
            cnx = mysql.connector.connect(user='cadmin', password='pi',
                                          host='localhost',
                                          database='controller')

            cnx1 = mysql.connector.connect(user='cadmin', password='pi',
                                           host='localhost',
                                           database='controller')
            cursor = cnx.cursor()
            cursor1 = cnx1.cursor()
            qry = 'select max(SchedKey)as maxkey from TScheduleMaster'
            cursor.execute(qry)
            for (maxkey) in cursor:
                newsc = maxkey[0] + 1
                print (maxkey)
                print (newsc)

            qry = 'select SchedKey, StepNumber, TargetTemp, RampRate, HoldTime, AlarmTemp from TSchedSteps where SchedKey=' + \
                str(sc) + ' order by Schedkey, StepNumber'
            cursor.execute(qry)

            for (SchedKey, StepNumber, TargetTemp,
                 RampRate, HoldTime, AlarmTemp) in cursor:

                #steplist=('['+ str(newsc)+','+str(StepNumber)+','+ str(TargetTemp)+','+str(RampRate)+','+str(HoldTime)+','+str(AlarmTemp)+']')
                steplist = (
                    str(newsc) +
                    ',' +
                    str(StepNumber) +
                    ',' +
                    str(TargetTemp) +
                    ',' +
                    str(RampRate) +
                    ',' +
                    str(HoldTime) +
                    ',' +
                    str(AlarmTemp))

                print (steplist)
                qry = 'insert into TSchedSteps VALUES(' + steplist + ')'
                print(qry)
                #qry = 'insert into TSchedSteps VALUES('+ str(newsc)+','+str(StepNumber)+','+ str(TargetTemp)+','+str(RampRate)+','+str(HoldTime)+','+str(AlarmTemp)+ ')'
                cursor1.execute(qry)
                cnx1.commit()
            cursor.close()
            cursor1.close()
            cnx.close
            cnx1.close()

    def editpgm():
        global PgmMsgout

        value = listbox.curselection()[0]

        compval = 'T'

        schedtype1 = (pgmlist[value])[1]

        if ord(schedtype1) == ord('T'):
            PgmMsgout('Please Select User Program.', 'red')
        else:
            schedkey1 = ((pgmlist[value])[0])

            framepgmselect.destroy()
            pgmselect(schedkey1, FireType)


#  When user selects Edit button from pgmload

def firepgm():
    global framefire

    #frame1 = Frame(root,height = 800, width = 500)
    # frame1.pack()
    #listbox = Listbox(frame1,height = 10, width = 30,selectmode = SINGLE)
##
    framefire = Frame(root, height=800, width=500)
    framefire.pack()
    rel = 'ridge'
    ButtonFuse = Button(
        framefire,
        text="Fuse",
        width=7,
        relief=rel,
        command=lambda: pgmload('FUSE'))
    ButtonFuse.pack()
    ButtonSlump = Button(
        framefire,
        text="Slump",
        width=7,
        relief=rel,
        command=lambda: pgmload('SLUMP'))
    ButtonSlump.pack()
    ButtonCast = Button(
        framefire,
        text="Cast",
        width=7,
        relief=rel,
        command=lambda: pgmload('CAST'))
    ButtonCast.pack()
    ButtonMelt = Button(
        framefire,
        text="Melt",
        width=7,
        relief=rel,
        command=lambda: pgmload('MELT'))
    ButtonMelt.pack()
    ButtonPolish = Button(
        framefire,
        text="Fire Polish",
        width=7,
        relief=rel,
        command=lambda: pgmload('POLISH'))
    ButtonPolish.pack()
    ButtonClay = Button(
        framefire,
        text="Clay",
        width=7,
        relief=rel,
        command=lambda: pgmload('CLAY'))
    ButtonClay.pack()
    ButtonEnamel = Button(
        framefire,
        text="Enamel",
        width=7,
        relief=rel,
        command=lambda: pgmload('ENAMEL'))
    ButtonEnamel.pack()
    button1 = Button(framefire, text="Quit",
                     command=lambda: root.destroy())
    button1.pack()

#  insert firepgm selection screen here


firepgm()
mainloop()

This snippet took 0.04 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).