-1

In my code I see that the Label is not being updated with the 'textvariable', despite I believe I'm doing it right (probably not!).

varmuTemperature = StringVar(value="default value")
self.Label = Label(Frame2, textvariable = varmuTemperature)
self.Label.pack()

This should show a label with "default value" written on it. The problem is that I don't see anything written. I have my code posted here.

import matplotlib
import matplotlib.artist as artists
import matplotlib.pyplot as plt
#import matplotlib.mlab as mlab
import scipy.stats

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, 
NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style

import numpy as np
import statistics

from tkinter import *
from tkinter import ttk

import serial
import time

import itertools

integer=0
xList = []
humidityList = []
humidityListHistogram = []
temperatureList = []
temperatureListHistogram = []
cnt=0

if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
    # this excludes your current terminal "/dev/tty"
    ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
    ports = glob.glob('/dev/tty.*')
else:
    raise EnvironmentError('Unsupported platform')

ser = serial.Serial()

style.use("seaborn-whitegrid")

#varmuTemperature = StringVar()
#varmuHumidity = StringVar()

f=plt.figure(0, figsize=(20,10))

humidityGraph = plt.subplot(224)
humidityGraph.set_title("Humidity vs Time")
humidityGraph.set_ylabel("Humidity RAW (Dec)")
humidityGraph.set_xlabel("Sample ()")


temperatureGraph = plt.subplot(223)
temperatureGraph.set_title("Temperature vs Time")
temperatureGraph.set_ylabel("Temperature RAW (Dec)")
temperatureGraph.set_xlabel("Sample ()")

humidityGraphHistogram = plt.subplot(222)
temperatureGraphHistogram = plt.subplot(221)
temperatureGraphHistogramNormal = temperatureGraphHistogram.twinx()
humidityGraphHistogramNormal = humidityGraphHistogram.twinx()

side_text = plt.figtext(0.93, 0.5, 'Text 1'+'\n'+'Text 2', bbox=dict(facecolor='white'))

plt.subplots_adjust(left = 0.05, right = 0.95, bottom = 0.05, top = 0.95, wspace = 0.16, hspace = 0.21)



class make_window():

    def __init__(self, *args, **kwargs):

        win = Tk()

        win.title("Test")
        win.state("zoomed")

        Frame1 = Frame(win)
        Frame1.pack()

        self.comboBoxAvailableCOMPort = ttk.Combobox(Frame1, width = 30)
        self.comboBoxAvailableCOMPort['values'] = []
        self.comboBoxAvailableCOMPort.pack(padx=5, pady=5, side = LEFT)

        self.buttonCheckComAvailable = Button(Frame1, text="Check COM Available", command = self.CheckComAvailable)
        self.buttonCheckComAvailable.pack(padx=5, pady=10, side = LEFT)

        self.buttonOpenCOMPort = Button(Frame1, text="Open COM Port", command = self.OnOpenCom)
        self.buttonOpenCOMPort.pack(padx=5, pady=10, side = LEFT)

        self.buttonCloseCOMPort = Button(Frame1, text="Close COM Port" , command = self.OnCloseCOM)
        self.buttonCloseCOMPort.pack(padx=5, pady=10,side = LEFT)

        self.CheckComAvailable()

        Frame2 = Frame(win, highlightbackground = "red", highlightcolor = "red", highlightthickness = 1)
        Frame2.pack()

        varmuTemperature = StringVar(value="default value")
        varmuTemperature.set("trerta")
        print(varmuTemperature.get())
        self.Label = Label(Frame2, textvariable = varmuTemperature)
        self.Label.pack()

        self.buttonCloseProgram = Button(Frame2, text="Close Program", command = self.OnCloseProgram)
        self.buttonCloseProgram.pack(expand=True, fill='x', anchor='s')


        Frame3 = Frame(win)
        Frame3.pack()

        canvas = FigureCanvasTkAgg(f, Frame3)
        canvas.get_tk_widget().pack(padx=5, pady=10, side=BOTTOM, expand = True)

        toolbar = NavigationToolbar2Tk(canvas, Frame3)
        toolbar.update()
        canvas._tkcanvas.pack(padx=5, pady=10,side = TOP)


    def CheckComAvailable(self):
        self.comboBoxAvailableCOMPort['values'] =[]
        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass
        self.comboBoxAvailableCOMPort['values'] += tuple(result)
        self.comboBoxAvailableCOMPort.set(result[0])

    def OnOpenCom(self):
        ser.baudrate = 115200
        ser.port = self.comboBoxAvailableCOMPort.get()
        try:
            ser.open()
            ser.readline()
            ser.write("#dut,0$\n".encode('utf-8'))
            ser.readline()
            ser.write("#v,1800,1800$\n".encode('utf-8'))
            ser.write("#W,77,08,07$\n".encode('utf-8'))
            ser.readline()

        except(OSError):
            print("COM Port in use")

    def OnCloseCOM(self):
        global xList
        global humidityList
        global temperatureList
        global humidityListHistogram
        global temperatureListHistogram
        global integer
        integer=0
        xList = []
        humidityList = []
        temperatureList = []
        ser.close()

    def OnCloseProgram(self):
        self.OnCloseCOM()
        exit()        

##    def toggle_geom(self,event):
##        geom=self.master.winfo_geometry()
##        print(geom,self._geom)
##        self.master.geometry(self._geom)
##        self._geom=geom


def animate(i):
    global integer
    global cnt
    try:
        ser.write(("#R,77,00,03$" + chr(10)).encode('utf-8'))
        humidityLine=ser.readline()
        inthumidityLine= int(humidityLine,16)
        if (inthumidityLine > 8388608):
            inthumidityLine = inthumidityLine - 16777216
        humidityList.append(inthumidityLine)
        humidityListHistogram.append(inthumidityLine)


        ser.write(("#R,77,03,03$" + chr(10)).encode('utf-8'))
        temperatureLine=ser.readline()
        LineHistogram = temperatureLine
        inttemperatureLine= int(temperatureLine,16)
        if (inttemperatureLine > 8388608):
            inttemperatureLine = inttemperatureLine - 16777216
        temperatureList.append(inttemperatureLine)
        temperatureListHistogram.append(inttemperatureLine)

        xList.append(integer)
        integer+=1

##################################################################################################################
##      Creates the HUMIDITY Graphics
##################################################################################################################

        humidityGraph.clear()
        humidityGraph.plot(xList,humidityList,'-b*', label = "Humidity RAW")
        humidityGraph.legend(loc='upper right', fancybox = True, frameon = True, shadow = True)
        humidityGraph.set_title("Humidity vs Time")
        humidityGraph.set_ylabel("Humidity RAW (Dec)")
        humidityGraph.set_xlabel("Sample ()")

        muHumidity = statistics.mean(humidityListHistogram)
        #print("Mean = " + str(muHumidity) + " ; N = " + str(len(humidityListHistogram)))
        #global varmuHumidity
        #varmuHumidity.set("Humidity: ")
        if (len(humidityListHistogram) > 1):
            sigmaHumidity = statistics.pstdev(humidityListHistogram)
        else:
            sigmaHumidity = 100
        humidityGraphHistogram.clear()
        nHumidity, binsHumidity, patchesHumidity = humidityGraphHistogram.hist(humidityListHistogram, 100, density=False, facecolor='blue', alpha=0.75, histtype = 'stepfilled')

        normalDistHumidity = scipy.stats.norm.pdf(binsHumidity, muHumidity, sigmaHumidity)
        humidityGraphHistogramNormal.clear()
        humidityGraphHistogramNormal.plot(binsHumidity, normalDistHumidity, 'r--')
        humidityGraphHistogram.set_title("Histogram for Humidity Data")
        humidityGraphHistogram.set_ylabel("Humidity RAW Counts (Dec)")
        humidityGraphHistogram.set_xlabel("BINS ()")
        humidityGraphHistogramNormal.set_ylabel("Normal Distribution")

##################################################################################################################
##      Creates the TEMPERATURE Graphics
##################################################################################################################

        temperatureGraph.clear()
        temperatureGraph.plot(xList,temperatureList,'-r*', label = "Temperature RAW")
        temperatureGraph.legend(loc='upper right', fancybox = True, frameon = True, shadow = True)
        temperatureGraph.set_title("Temperature vs Time")
        temperatureGraph.set_ylabel("Temperature RAW (Dec)")
        temperatureGraph.set_xlabel("Sample ()")



        muTemperature = statistics.mean(temperatureListHistogram)
        #global varmuTemperature
        #varmuTemperature.set("Temperature: " )
        if (len(temperatureList) > 1):
            sigmaTemperature = statistics.pstdev(temperatureListHistogram)
        else:
            sigmaTemperature = 100
        temperatureGraphHistogram.clear()
        nTemperature, binsTemperature, patchesTemperature = temperatureGraphHistogram.hist(temperatureListHistogram, 100, density=False, facecolor='red', alpha=0.75, histtype = 'stepfilled')

        normalDistTemperature = scipy.stats.norm.pdf(binsTemperature, muTemperature, sigmaTemperature)
        temperatureGraphHistogramNormal.clear()
        temperatureGraphHistogramNormal.plot(binsTemperature, normalDistTemperature, 'b--')
        temperatureGraphHistogram.set_title("Histogram for Temperature Data")
        temperatureGraphHistogram.set_ylabel("Temperature RAW Counts (Dec)")
        temperatureGraphHistogram.set_xlabel("BINS ()")
        temperatureGraphHistogramNormal.set_ylabel("Normal Distribution")


        if (cnt > 100):
            xList.pop(0)
            humidityList.pop(0)
            temperatureList.pop(0)
        cnt+=1
    except(OSError):
        bla=0



win = make_window()
ani = animation.FuncAnimation(f, animate, interval = 300)
make_window.mainloop()

Debugging a bit and start commenting lines of code, I see that the problem may come from the

f=plt.figure(0, figsize=(20,10))

Commenting this line (and all dependencies of this) makes the Label to be written. Can someone help here, please? I don't get why the graphics can interfere in the Label. Thanks a lot.

cdlane
  • 40,441
  • 5
  • 32
  • 81
rpecas
  • 177
  • 1
  • 5
  • 2
    You've posted way too much code. Please try to reduce it down to a [mcve]. – Bryan Oakley Oct 18 '18 at 12:50
  • 1
    When asking a question about a specific problem please reduce your code to the parts involved. All we need is your label the textvar and whatever should be updating that var. – Mike - SMT Oct 18 '18 at 13:32

1 Answers1

0

The general problem seems to be your management of instance variables and objects. You keep around as self.* variables, things you'll never need to reference again, like buttonCheckComAvailable, but fail to make self.* variables for things, like varmuTemperature, that you will need to reference later.

Object-wise, you do things that don't make sense:

make_window.mainloop()

as make_window is an object class, not an instance, and an instance of the class make_window won't respond to mainloop anyway as it contains a window but isn't one itself.

Here's my MCVE for your example code that makes varmuTemperature an instance variable and, just for demonstration purposes, sets it when the various buttons on the interface are clicked so you can see it's working:

from tkinter import *
from tkinter import ttk

class make_window():

    def __init__(self):

        self.win = Tk()

        self.win.title("Test")
        self.win.state("zoomed")

        Frame1 = Frame(self.win)

        self.comboBoxAvailableCOMPort = ttk.Combobox(Frame1, width=30)
        self.comboBoxAvailableCOMPort['values'] = []
        self.comboBoxAvailableCOMPort.pack(padx=5, pady=5, side=LEFT)

        Button(Frame1, text="Check COM Available", command=self.CheckComAvailable).pack(padx=5, pady=10, side=LEFT)

        Button(Frame1, text="Open COM Port", command=self.OnOpenCom).pack(padx=5, pady=10, side=LEFT)

        Button(Frame1, text="Close COM Port", command=self.OnCloseCom).pack(padx=5, pady=10, side=LEFT)

        Frame1.pack()

        Frame2 = Frame(self.win, highlightbackground="red", highlightcolor="red", highlightthickness=1)

        self.varmuTemperature = StringVar(value="default value")
        Label(Frame2, textvariable=self.varmuTemperature).pack()

        Button(Frame2, text="Close Program", command=self.OnCloseProgram).pack(expand=True, fill='x', anchor='s')

        Frame2.pack()

    def CheckComAvailable(self):
        self.varmuTemperature.set("CheckCom")

    def OnOpenCom(self):
        self.varmuTemperature.set("OpenCom")

    def OnCloseCom(self):
        self.varmuTemperature.set("CloseCom")

    def OnCloseProgram(self):
        self.OnCloseCom()
        exit()

window = make_window()

window.win.mainloop()
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • Thank you very much for you time trying to solve my issue @cdlane. I can see the label being written if I reduce the code to just the Buttons and Frames, but if I include the graphics (dependencies of the variable 'f'), then it's not being shown anymore (this was the reason I put the whole code here). – rpecas Oct 19 '18 at 07:34